Power Shell "Missing Expression after unary operator '-' "
Repeat foreach loop after all iteration completed in Powershell
ComboBox Default value
Helou Guys,
pls, how can set a default value from combox?
Here is a part of the code
$TaskSequence_Selector_Array = @("Task Sequence 1","Task Sequence 2") $TaskSequence_Selector = New-Object System.Windows.Forms.ComboBox $TaskSequence_Selector.Location = New-Object System.Drawing.Size(10,35) $TaskSequence_Selector.Size = New-Object System.Drawing.Size(180,20) $TaskSequence_Selector.DropDownHeight = 200 $TaskSequence_Selector.Text = "Choose Task Sequence:" $TaskSequence_Selector.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList; $TaskSequence_Selector.SetSelected(1,$true) $TaskSequence_Selector.Font = New-Object System.Drawing.Font("Arial",10,[System.Drawing.FontStyle]::Regular) foreach($TaskSequence_DropDown in $TaskSequence_Selector_Array){ $TaskSequence_Selector.Items.Add($TaskSequence_DropDown) } $Form_MainWindow.Controls.Add($TaskSequence_Selector)
Now the ComboBox is blank
How to make some value as default, for example 'Task Sequence 1'?
Thanks for help.
Copying SELF permissions from one user to another in AD
Hello there! I'm having a problem with the security in Windows. I need to give specific SELF permissions in every user of my Active Directory. Through GUI I've written this permissions in one user, but I need to give those permissions to another 1300 users.
I'm using PowerShell to write this script but after googling a lot, I can't manage it to work because I don't really understand every type of data that uses every command. I got this right now:
import-module activedirectory
$ace = (get-acl "ad:CN=XXX,OU=prueba,DC=test,DC=es")
$users = get-aduser -searchbase "OU=test-uo,OU=prueba,DC=test,DC=es" -filter *
foreach ($user in $users) {
$acl = (get-acl ad:$user)
$acl.AddAccessRule(($ace.access | where { $_.IdentityReference -eq 'NT AUTHORITY\SELF' }))
set-acl -AclObject $acl $user
}
If someone can help me or point me in the right direction I would really apreciate it.
See you.
Why not able to change timer for saver?
Referring to following link, after running those coding, I would like to know on why not able to change timer for screensaver.
<# .SYNOPSIS This script can be used to set the Screen Saver Timeout interval. .DESCRIPTION This script can be used to set the Screen Saver Timeout interval. .EXAMPLE C:\PS> C:\Script\Set_Screen_Saver_Timeout.ps1 100 Sets the ScreenSaverTimeOut value as 100. #> Param([int]$value) $path = ‘HKCU:\Control Panel\Desktop’ $name = ‘ScreenSaveTimeOut’ #To get the ScreenSaveTimeOut value. $old_value=(Get-ItemProperty -path $path -name $name).$name echo “Old ScreenSaveTimeout: $old_value” #To set the new ScreenSaveTimeOut value. Set-ItemProperty -Path $path -name $name -value $value #To get the new ScreenSaveTimeOut value. $new_value=(Get-ItemProperty -path $path -name $name).$name echo “New ScreenSaveTimeout: $new_value”
Does anyone have any suggestions?
Thanks in advance for any suggestions
REF : http://www.techcrafters.com/scripts/windows-system-management/set-screen-saver-timeout.html
Thanks in advance for any suggestions
AD Powershell query to copy one attribute value to another for the users in a CSV file.
I have a CSV file that looks like this:
fname1lname1@companyemail.com
fname2lname2@companyemail.com ...
I would like to loop through each email address and query AD for that address and then copy theemployeenumber attribute value to employeeid attribute in AD for each email address in the csv file.
AD Backup Date
Hello All,
In the following article http://technet.microsoft.com/en-us/library/jj130668(v=ws.10) it is advised to "Monitor Active Directory dSASignature has been set for each naming context (NC) on each domain controller being backed up in the forest."
Does someone how to decode the value in dSASignature attribute to find when naming context was backed up. If we use an repadmin /showbackup * we get all the needed information, but if this value can be decoded inside an VBscript this would be lot more easier to manage rather than redirecting the output of repadmin to an text file and parsing the output of all DCs to know which NC was backed when.
Thanks In Advance
Raghu
first find then change folder permissions within file structure using scripts or software
Hello, I need to know if there is a script out there that can find builtin\Authenticated Users permissions assigned in file system folders and change its permissions?
We have set builtin\Authenticated Users on various folders within file shares to List folder/Read data access only. We need to now find these folders that have Authenticated Users permissions assigned and change them to Read access (includes: List folders/read access, Read attributes, Read Extended Attributes).
This is on a new NAS server that does not behave like previous NAS servers. So we now need to reset Authenticated Users permissions in order to allow the same access as before.
If this can only be done using software please help point me in the right direction.
Thanks for any help that I can get on this issue.
Script for Outlook maintenanceand PST file repair
I am looking to do a script for the following
- Repair pst file, no backup, repeat until no errors
- Archive sent items older than 60 days to certain path
- Archive deleted items older than 60 days to certain path
- Compact pst file
- send log of this to email
I would like to get this done without the use of commercial utils and just nice clean scripting
How Password used in powershell securely
Hi ,
Good Day !
I'm finding difficultly in using password securely in poweshell script.
Looking for an option to user credential in powershell in more secure way.
Please advice how i can achieve it.
Thanks.
shutdown service : etl trace
temporary, i want to stop .etl trace
it's possible to use administrative tools services for shutdown etl trace like :
VsEtwService120
Wecsvc
WdiSystemHost
EventLog
pla
diagnosticshub.standardcollector.service
DPS
WdiServiceHost
EventSystem
VSStandardCollectorService150
wmiApSrv
CoreMessagingRegistrar
ShellHWDetection
DiagTrack
PerfHost
SENS
WerSvc
Winmgmt
but do Wecsvc or eventlog are the best choice for unload all etl trace and all session are off line ? the problem is if not i load my script on offline user session using a tool like windows pe.
SetACL finished with error(s):
Hi All,
I have written the below as .bat script to load the registry and give permissions.
cpau -u Service -p "password" -ex "cmd /c sleep 2" -lwp -wait
reg load HKLM\Service_USER "%SystemDrive%\Users\Service\NTUSER.DAT"
setacl -on "hklm\Service_USER\Software\Microsoft\Windows\CurrentVersion\Policies" -ot reg -actn ace -ace "n:.\Service;p:full"
When run this script am getting below error:
CPAU V01.11.00cpp
Current Security Context: Administrator
Process Created...
The command completed successfully.
ERROR: The process cannot access the file because it is being used by another process.
SetACL finished with error(s):
SetACL error message: Opening a registry key failed
Operating system error message: The system cannot find the file specified.
I tried to give sleep 100 command after registry load(reg load) thinking that it is taking time to load NTUSER.DAT but still am getting the same error.
If anyone have the idea to solve the issue. Please share the ideas.
Thanks,
General Question / Commandlet / Object Output - get-nettcpconnection / get-process
Looking to piece together two things:
The get-process command - which will list running processes on a device, and the get-nettcpconnection - which will show ports that, based on the filter/command, are listening.
What I'm finding is that when I manually enter the commands I want to a command line - the output is readable and useful.
When I pipe the commands to a variable (to step through each line when required), the output is less than visually appealing - while I know what I'm looking at, the folks I would turn this over to may initially *not*.
What is it about the way I'm doing this that is creating aesthetically unfriendly output?
Thanks in advance, I appreciate all suggestions, pointers and information
$listenerlist = (get-nettcpconnection | ? State -Like Listen | Sort-Object OwningProcess) foreach ($listeneritem in $listenerlist) { write-host "" Write-Host $listeneritem (Get-Process -Id $listeneritem.OwningProcess | Sort-Object Name) }
Sample Output:
MSFT_NetTCPConnection (InstanceID = "0.0.0.0??8194??0.0.0.0??0")
393 31 6412 11460 15248 0 RouterNT
Powershell Script to Restart Computer After 3 days
Hi guys,
I need a powershell script to restart computers that have been up for over three days forcefully.
I have the Vbs script below; however when I apply the script as a policy, the computers are in a continuous restart loop.
Kindly help to fix
'Restart the local device if it has not been shutdown in more than X Hours'strComputer = "."
X = 72
set objWMIDateTime = CreateObject("WbemScripting.SWbemDateTime")
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colOS = objWMI.InstancesOf("Win32_OperatingSystem")
for each objOS in colOS
objWMIDateTime.Value = objOS.LastBootUpTime
'Check the device uptime in hours
UptimeHours = TimeSpan(objWMIDateTime.GetVarDate,Now)
Next
'Check to see if > than X hours and restart if true
If UptimeHours > X Then
MsgBox "Your computer has not been restarted in over " & X & " hours, to ensure best performace your computer will now automatically restart", vbExclamation + vbOKOnly, "Sahara ITHelpdesk"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Shutdown)}!\\" & _
strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
objOperatingSystem.Reboot()
Next
Else
End if
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function TimeSpan(dt1, dt2)
' Function to display the difference between
' 2 dates in hh:mm:ss format
If (isDate(dt1) And IsDate(dt2)) = false Then
TimeSpan = "00:00:00"
Exit Function
End If
seconds = Abs(DateDiff("S", dt1, dt2))
minutes = seconds \ 60
hours = minutes \ 60
minutes = minutes mod 60
seconds = seconds mod 60
if len(hours) = 1 then hours = "0" & hours
TimeSpan = hours
End Function
Infinite PowerShell loop using too much memory
I created the following PowerShell script with an infinite loop to provide a log of when we are experiencing a NSlookup failure.
ForEach ($varDomain in $arrDomains){
if (-Not (Resolve-DnsName $varDomain -ErrorAction SilentlyContinue)){
$varOutput = "NSlookup failed on " + (Get-Date).DateTime + " for $varDomain"
$varOutput | Out-File -filepath C:\Scripts\NSlookupFailureLog.txt -Append
}
}
}
The script works great and the resulting log file is exactly what we need to give to the hardware firewall supplier to prove the hardware firewall is causing the intermittent webpage connection failures. The only problem with running the script is the fact that the memory usage grows until the system slows down and other users complain. Overnight the memory usage grew to 30 GB. After searching online, I have been unable to find a solution. What needs to be changed in the script to stop the large memory usage? Thanks for your help with this.
PowerShell and CSV
Hello everyone :),
I am building a powershell script that make my job more optimal.
My powershell script connect to MSol service. But i am trying to use a csv file wich contains name, username, and password of Office365 tenant of the client.
csv file have 3 headers : Nom,username,mdpasse and when i type the name (nom) i got the good informations.
In first, the script ask for the name of client, and then search in the file the good row, wich contains informations about the client (username and password). Now the script works, he find informations about the client, but it format the result as table or with @and brackets.
So i did some modifications in the script but i know this is not the good way to do because he let some space in the result.
My script
$choixDuClient = Read-Host "Veuillez ecrire en minuscules le nom du client " $importLogins = import-csv -Path C:\loginsOffice365.csv -Delimiter ";" $nomUtilisateur = $importLogins | Where-Object Nom -eq $choixDuClient | Select-Object username | % { ($_ | Out-String).Trim() -replace '@\{|\}' } | % { ($_ | Out-String).Trim() -replace 'username' } | % { ($_ | Out-String).Trim() -replace '--------' } $motdepasseUtilisateur = $importLogins | Where-Object Nom -eq $choixDuClient | Select-Object mdpasse | % { ($_ | Out-String).Trim() -replace '@\{|\}' } | % { ($_ | Out-String).Trim() -replace 'mdpasse' } | % { ($_ | Out-String).Trim() -replace '--------' } $tenant = 'mytenant' $userName = $nomUtilisateur $password = $motdepasseUtilisateur $pass = ConvertTo-SecureString -AsPlainText $Password -Force $SecureString = $pass $MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString function ConnexionOffice365{ $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $MySecureCreds -Authentication Basic -AllowRedirection if ($Session -ne $null) { Write-Host 'Connexion au tenant : ' -NoNewline; Write-Host -ForegroundColor Yellow $tenant -NoNewline; Write-Host "`r`n" Write-Host 'Etat de la connexion : ' -NoNewline; Write-Host -ForegroundColor green 'Ok' $msonline = Connect-MsolService -Credential $MySecureCreds if ($msonline -ne 'Authentication Error: Unexpected authentication failure') { Write-Host 'Services Microsoft Online :' -NoNewline; Write-Host -ForegroundColor Green " Activés`r`n" } } else { Write-Host -ForegroundColor Red "Echec de la connexion" } } function licencesSurTenant { Get-MsolAccountSku } function Show-Menu { $procruser = Write-Host -ForegroundColor Yellow '1.' -NoNewline ; Write-Host 'Créer un utilisateur' $propchmdp = Write-Host -ForegroundColor Yellow '2.' -NoNewline; Write-Host 'Changer Mot de Passe' $propchlic = Write-Host -ForegroundColor Yellow '3.' -NoNewline; Write-Host 'Changer de Licence' $deconnexion = Write-Host -ForegroundColor Yellow '4.' -NoNewline; Write-Host "Deconnexion `r`n" $choice = Read-Host Switch ($choice) {"1" { $nom = Read-Host "Veuillez entrez le nom " $prenom = Read-Host "Veuillez entrez le prenom " $affichage = Read-Host "Veuillez entrez le nom d'affichage " $mail = Read-Host "Veuillez entre le mail à créer " $motdepasse = Read-Host "Veuillez entrer le mot de passe " Get-MsolAccountSku | Format-Table $licence = Read-Host "Veuillez choisir la licence à assigner " New-MsolUser -DisplayName $affichage -FirstName $prenom -LastName $nom -UserPrincipalName $mail -UsageLocation "FR" -LicenseAssignment $licence -Password $motdepasse Show-Menu }"2" { $randomPassword = Write-Host -ForegroundColor Yellow 'a.' -NoNewline; Write-Host 'Mot de passe aléatoire' $chosenPassword = Write-Host -ForegroundColor Yellow 'b.' -NoNewline; Write-Host 'Choisir le mot de passe' $choixmdp = Read-Host if ($choixmdp -eq 'a') { Get-MsolUser| Format-Table $passwordMailChangeRandom = Read-Host "Merci d'entrer le mail " Set-MsolUserPassword -UserPrincipalName $passwordMailChangeRandom -ForceChangePassword } else { Get-MsolUser | Format-Table $passwordMailChange = Read-Host "Merci d'entrer le mail " $newPassword = Read-Host "Entrer le nouveau mot de passe " Set-MsolUserPassword -UserPrincipalName $passwordMailChange -NewPassword $newPassword } Show-Menu }"3" { $accLicense = Read-Host "Entrez le nom d'utilisateur du compte qui doit subir un chagement de licence " Write-Host "Voici les licences sur le tenant: " ; licencesSurTenant Write-Host "Voici les licences dont dispose l'utilisateur " $accLicense ; (Get-MsolUser -UserPrincipalName $accLicense).licenses.accountskuid $ajoutLicence = Read-Host "Selectionnez la licence à ajouter " $retraitLicence = Read-Host "Selectionner la licence à retirer " Set-MsolUserLicense -UserPrincipalName $accLicense -AddLicenses {$tenant}:{$ajoutLicence} -RemoveLicenses {$tenant}:{$retraitLicence} Show-Menu }"4" { Remove-PSSession $Session } } } ConnexionOffice365 licencesSurTenant Show-Menu
So when my script is trying to retrieve the good ID and password, it works well the problem is (i think) the format.
Sorry for my English.
Can you help me please?
Thank's a lot.
Best Regards.
Yoann
Search in huge directorystructore for filenames listed in a .csv file
Hi Scripting Guys!
I need to verify if thousands of pictures on a remote disk exists somewhere on my laptop.
So basically I need to compare two very different directorystructures.
I think this is a little bit complex, since I have to import the .csv to Powershell - for every single filename I need to make a recursive search in my laptop.
On the external disk I have approx 100.000 pictures, but the directorystructure on this disk is much different than the structure on my computer.
I have extracted all the filenames from this external disk in a .csv file.
For every single filename listed in the .csv file - I need to know if the files exists somewhere on my laptop, and the whole directory.
It´s necessary for me to know, if there are any files, that are missing on my laptop.
This is the structure of my .csv file:
IMG_4761.JPG
IMG_4762.JPG
IMG_4763.JPG
IMG_4764.JPG
Best regards Soeren Jensen
Generating a csv file with URLs from within a PDF file
Hello,
Hands and feet technician chiming in from Montreal.
Love how powershell smoothes out repetitive and time consuming tasks.
I have a feeling I will need itext for this one.
Tackling the wall of PDF issue, looking to write a script that will:
Parse a PDF runbook, and create a new onenote file as per:
Title of the section matching the PDF File Name
Title of each new section matching the types of urls found:
Section Title: SharePoint Links, Content:
Section Title as Heading 3 (unless listed in above entry)
Link Description (Heading 4) | URL icon with an embedded hyperlink
I appreciate your insights as always.
Not Enough Quota is Available to Process This Command
org.openqa.selenium.os.OsProcess checkForError SEVERE: org.apache.commons.exec.ExecuteException: Execution failed (Exit value: -559038737. Caused by java.io.IOException: Cannot run program "C:\jenkins\workspace\xome_valuations_test\xv-tests\resources\drivers\chromedriver\win32\79.0.3945.36\chromedriver.exe" (in directory "."): CreateProcess error=1816, Not enough quota is available to process this command) org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start. Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: 'WIN-EN1HK1FMAVC', ip: '10.29.16.241', os.name: 'Windows Server 2012 R2', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_231'
Script para obtener datos de Excel
Buenas Noches, cómo va? Les cuento, tengo un archivo Excel con datos (Nombre y Apellido, email, link de CV, Link de audio, etc). Necesito realizar un script que abra este archivo, lea linea por linea y ejecute lo siguiente: busque los datos, cree una carpeta en el directorio principal con el nombre y apellido de la persona que esta leyendo, descargue el link del CV y los guarde en su directorio, etc). Al terminar, que lea la siguiente linea del archivo Excel.
Existe una forma de hacerlo? Por ejemplo: powershell, java, php, etc?
Les agradezco me puedan ayudar.
Saludos
Sergio
If God will send his angels