Powershell, Windows
Powershell encryption decryption
Deux méthodes pour encrypter/decrypter une variable: $MyPswd = « password1234 » ConvertTo-SecureString $MyPswd -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath « $chemin\pass.txt » $password = Get-Content « $chemin\pass.txt » | ConvertTo-SecureString $bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) $pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd) Write-Host $pswd rm « $chemin\pass.txt » Add-Type -assembly System.Security $passwordBytes = [System.Text.Encoding]::Unicode.GetBytes(« Open Sesame ») $entropy = [byte[]](1,2,3,4,5) $encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect($passwordBytes, $entropy, ‘CurrentUser’) $encrytpedData | Set-Content -enc byte .\password.bin $encrytpedData = Get-Content -enc byte .\password.bin $unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( $encrytpedData, $entropy, ‘CurrentUser’) $password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData) $password function Set-Key { param([string]$string) $length = $string.length $pad = 32-$length if (($length -lt 16) -or ($length -gt 32)) {Throw « String must be between 16 and 32 characters »} $encoding = New-Object System.Text.ASCIIEncoding $bytes = $encoding.GetBytes($string + « 0 » * $pad) return $bytes } function Set-EncryptedData { param($key,[string]$plainText) $securestring = new-object System.Security.SecureString $chars = $plainText.toCharArray() foreach ($char in $chars) {$secureString.AppendChar($char)} $encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key return $encryptedData } function Get-EncryptedData { param($key,$data) $data | ConvertTo-SecureString -key $key | ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))} } #Encrypt $plainText = « Some Super Secret Password » $key = Set-Key « AGoodKeyThatNoOneElseWillKnow » $encryptedTextThatIcouldSaveToFile = Set-EncryptedData -key $key -plainText $plaintext $encryptedTextThatIcouldSaveToFile #Decrypt $DecryptedText = Get-EncryptedData -data $encryptedTextThatIcouldSaveToFile -key $key $DecryptedText Voilà vous pouvez encrypter vos données sensibles…
Read MorePowershell, Windows
Powershell envoyer un email
Envoyer un email avec Powershell: $attachfile = New-Item -type file -force « $chemin\attachment.txt » Write-Output « attachment file example » | Out-File -Append $attachfile $to = « name@domain.com » $from = « name@domain.com » $smtp = « 192.168.1.1 » $subject = « Subject » $body = « Body » Send-MailMessage -to $to -From $from -Attachments « $chemin\attachment.txt » -SmtpServer $smtp -Subject $subject -Body $body rm « $chemin\attachment.txt » Assez simple finalement !
Read MorePowershell, Windows
Powershell comparaison de fichier
Une petie comparaison de fichier pour faire apparaître les différences et similitudes: $file1 = « $chemin\left.txt » $file2 = « $chemin\right.txt » Write-Output « equalite » | Out-File -Append $file1 Write-Output « equal » | Out-File -Append $file1 Write-Output « diff1 » | Out-File -Append $file1 Write-Output « equalite » | Out-File -Append $file2 Write-Output « equal » | Out-File -Append $file2 Write-Output « diff2 » | Out-File -Append $file2 Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘==’} | ForEach-Object {$_.InputObject} | Out-File « result_equal.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘=>’} | ForEach-Object {$_.InputObject} | Out-File « result_right.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘<=’} | ForEach-Object {$_.InputObject} | Out-File « result_left.txt » $compequal = gc « result_equal.txt » $compleft = gc « result_left.txt » $compright = gc « result_right.txt » $context = Get-Content $file1 | Select-String equalite -Context 2 Write-host $context Write-Host « Comparaison ==: » $compequal Write-Host « Comparaison:=> » $compleft Write-Host « Comparaison:<= » $compright rm « left.txt » rm « right.txt » rm « result_equal.txt » rm « result_right.txt » rm « result_left.txt » Très pratique !
Read MorePowershell, Windows
Powershell sorting de fichier
Petit aperçu du sorting de fichier: $createsortfile = New-Item -type file -force « $chemin\sort.txt » Write-Output « chiffre;lettre;date » | Out-File -Append $createsortfile Write-Output « 10;a;2012-04-05 » | Out-File -Append $createsortfile Write-Output « 11;z;2012-04-01 » | Out-File -Append $createsortfile Write-Output « 13;b;2012-04-02 » | Out-File -Append $createsortfile Import-csv « $chemin\sort.txt » -delimiter « ; » | sort-object date,lettre | export-csv « $chemin\sort.csv » $resultsort = gc « $chemin\sort.csv » Write-Host $resultsort rm « $chemin\sort.* » ça reste simple comme exemple, on est d’accord…
Read MoreAdministration système, Powershell, Windows
Lancer un pool de 100 ping (ou autre ou +/-…)
Lancer des Threads en background avec powershell $job = @(0..100) for ($i =0; $i -lt 100; $i++){ $job[$i] = start-job { ping 127.0.0.1 } }
Read MoreAdministration système, Powershell, Windows
Variables Réservées
Variables inutilisables car réservées par le système: $PID $Profile $NestedPromptLevel $MyInvocation $LastExitCode $Host $Home $ExecutionContext $Event $Error $ConsoleFileName $^ $? $$
Read MoreAdministration système, Powershell, Windows
Parsing Ping Results
Exemple pour parser le résultat d’un ping; $a = ping 127.0.0.1 | Select-String « Paquets » $b = $a.ToString() $c= $b.Substring($b.IndexOf(« envoyés = « )+10,1) $d= $b.Substring($b.IndexOf(« reçus = « )+8,1) $e= $b.Substring($b.IndexOf(« perdus = « )+9,1) Write-Host « nombre de ping OK = $c » Write-Host « nombre de ping KO = $d » Write-Host « nombre de ping Perdu = $e » TTL moyen: $a2 = ping 127.0.0.1 | Select-String « Réponse » $i = 0 $total = 0 foreach ($ligne in $a2) { Write-Host $ligne; $ttl = $ligne.ToString().Substring($ligne.ToString().IndexOf(« TTL= »)+4,3) -as [int]; $total = $total + $ttl; $i++; Write-Host $ttl } $ttlmedium = $total/$i Write-Host « TTL medium = $ttlmedium » Enjoy !!
Read MoreAdministration système, Powershell, Windows
Information sur l’OS
Quelques informations intéressantes: $result = Get-WmiObject Win32_OperatingSystem -computer localhost $resultsvc = Get-WmiObject win32_service -computer localhost $servicepack = $result.servicepackmajorversion $version = $result.Version Write-Host $version Write-Host $servicepack Write-Host $resultsvc Dernier boot: Get-WmiObject Win32_OperatingSystem | select @{Name= »BootTime » Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} Taille de tous les disques: $dsk= Get-WmiObject Win32_LogicalDisk « Drive Letter Size GB » foreach ( $drive in $dsk ) { « Drive = » + $drive.Name + ` » Size = » + [int]($drive.Size/1073741824)} Date d’installation de l’OS: ([WMI] »).ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).InstallDate) Enjoy !!
Read MoreAdministration système, Powershell, Windows
Envoyer un email
Voilà comment envoyer un Email avec pièce jointe: $attachfile = New-Item -type file -force « C:\attachment.txt » Write-Output « attachment file example » | Out-File -Append $attachfile $to = « admin@exatek.fr » $from = « admin2@exatek.fr » $smtp = « 127.0.0.1 » $subject = « Subject » $body = « Body » Send-MailMessage -to $to -From $from -Attachments « C:\attachment.txt » -SmtpServer $smtp -Subject $subject -Body $body Enjoy !!
Read MoreAdministration système, Powershell, Windows
Lecteur réseau
Monter/Démonter un lecteur réseau: $net = new-object -ComObject WScript.Network $net.MapNetworkDrive(« L: », « \\NOM_MACHINE\d$ », $false, « User », « Password ») Set-Location L: $dir = gci . Write-Host $dir Set-Location $chemin $lectest = Get-PSDrive | Where {$_.Name -eq « L »} if ($lectest -ne $null) { $net = new-object -ComObject WScript.Network $net.RemoveNetworkDrive(« L: », $true) } Enjoy !!
Read MoreAdministration système, Powershell, Windows
PoSH substring
Exemples différents d’utilisation de « substring » $install =”foo_Install” $pos = $install.IndexOf(« Install ») $leftPart = $install.Substring(0, $pos) Write-Host $leftPart $rightPart = $install.Substring($pos+1) $leng = $install.Length $installtrimbylenght = $install.Substring($leng-7) Write-Host $installtrimbylenght $split = $install.Split(« _ ») Write-Host « partie 1: « $split[0] Write-Host « partie 2: « $split[1] $installreplace = $install.Replace(« _ », »@ ») Write-Host $installreplace
Read MoreAdministration système, Powershell, Windows
Encryption des mots de passe
Première méthode : $MyPswd = « password1234 » $chemin = « C:\ » ConvertTo-SecureString $MyPswd -AsPlainText -Force | ConvertFrom-SecureString | Out-File -FilePath « $chemin\pass.txt » $password = Get-Content « $chemin\pass.txt » | ConvertTo-SecureString $bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) $pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd) Write-Host $pswd rm « $chemin\pass.txt » Deuxième méthode: # Stick password into DPAPI storage once – accessible only by current user Add-Type -assembly System.Security $passwordBytes = [System.Text.Encoding]::Unicode.GetBytes(« Open Sesame ») $entropy = [byte[]](1,2,3,4,5) $encrytpedData = [System.Security.Cryptography.ProtectedData]::Protect($passwordBytes, $entropy, ‘CurrentUser’) $encrytpedData | Set-Content -enc byte .\password.bin # Retrieve and decrypted password $encrytpedData = Get-Content -enc byte .\password.bin $unencrytpedData = [System.Security.Cryptography.ProtectedData]::Unprotect( $encrytpedData, $entropy, ‘CurrentUser’) $password = [System.Text.Encoding]::Unicode.GetString($unencrytpedData) $password Troisième méthode: function Set-Key { param([string]$string) $length = $string.length $pad = 32-$length if (($length -lt 16) -or ($length -gt 32)) {Throw « String must be between 16 and 32 characters »} $encoding = New-Object System.Text.ASCIIEncoding $bytes = $encoding.GetBytes($string + « 0 » * $pad) return $bytes } function Set-EncryptedData { param($key,[string]$plainText) $securestring = new-object System.Security.SecureString $chars = $plainText.toCharArray() foreach ($char in $chars) {$secureString.AppendChar($char)} $encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key return $encryptedData } function Get-EncryptedData { param($key,$data) $data | ConvertTo-SecureString -key $key | ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))} } #Encrypt $plainText = « Some Super Secret Password » $key = Set-Key « AGoodKeyThatNoOneElseWillKnow » $encryptedTextThatIcouldSaveToFile = Set-EncryptedData -key $key -plainText $plaintext $encryptedTextThatIcouldSaveToFile #Decrypt $DecryptedText = Get-EncryptedData -data $encryptedTextThatIcouldSaveToFile -key…
Read MoreAdministration système, Powershell, Windows
Comparaison de fichiers
Petits exemples de comparaisons de fichiers: $chemin = « C:\ » $file1 = « $chemin\left.txt » $file2 = « $chemin\right.txt » Write-Output « equalite » | Out-File -Append $file1 Write-Output « equal » | Out-File -Append $file1 Write-Output « diff1 » | Out-File -Append $file1 Write-Output « equalite » | Out-File -Append $file2 Write-Output « equal » | Out-File -Append $file2 Write-Output « diff2 » | Out-File -Append $file2 Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘==’} | ForEach-Object {$_.InputObject} | Out-File « result_equal.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘=>’} | ForEach-Object {$_.InputObject} | Out-File « result_right.txt » Compare-Object $(Get-Content « left.txt ») $(Get-Content « right.txt ») -IncludeEqual | Where {$_.SideIndicator -eq ‘<=’} | ForEach-Object {$_.InputObject} | Out-File « result_left.txt » $compequal = gc « result_equal.txt » $compleft = gc « result_left.txt » $compright = gc « result_right.txt » $context = Get-Content $file1 | Select-String equalite -Context 2 Write-host $context Write-Host « Comparaison ==: » $compequal Write-Host « Comparaison:=> » $compleft Write-Host « Comparaison:<= » $compright rm « left.txt » rm « right.txt » rm « result_equal.txt » rm « result_right.txt » rm « result_left.txt »
Read MoreAdministration système, Powershell, Windows
Traiter des dates
Formatage de date: $datestring = Get-Date -uformat « Date: %d-%m-%Y Heure: %H:%M:%S Millis: %s » Write-Host $datestring Fonction pour faire des timestamp pendant le traitement (avec exemple d’utilisation) ######fonction temps function GetElapsedTime() { $runtime = $(get-date) – $script:StartTime $retStr = [string]::format(« {0} days, {1} hours, {2} minutes, {3}.{4} seconds », ` $runtime.Days, ` $runtime.Hours, ` $runtime.Minutes, ` $runtime.Seconds, ` $runtime.Milliseconds) $retStr } #on récupère le temps courant $script:startTime = get-date #on affiche le temps écoulé $(GetElapsedTime) Ajouter jours/mois à une date $currentdate = [datetime]::now $currentdate.AddDays(10) $currentdate.AddMonths(2)
Read MoreAdministration système, Powershell, Windows
Fonctions Requêtes AD Powershell
Quelques fonctions pour extraire des informations de l’AD : Liste d’une catégorie d’objet: function ListADCategoryArg { $filtre = « (objectCategory=$args) » $domaine = New-Object System.DirectoryServices.DirectoryEntry $chercheur = New-Object System.DirectoryServices.DirectorySearcher $chercheur.SearchRoot = $domaine $chercheur.PageSize = 10 $chercheur.Filter = $filtre $prop = « name » foreach ($i in $prop){$chercheur.PropertiesToLoad.Add($i)} $colResults = $chercheur.FindAll() foreach ($objResult in $colResults) { $objItem = $objResult.Properties # Sortie vers l’écran write-host $objItem.name } } ListADCategoryArg Group Lister les membres de : function ListmemberOf { $Dom = ‘LDAP://OU=$args,dc=xxxx,dc=zzzz »‘ $Root = New-Object DirectoryServices.DirectoryEntry $Dom $i=0 # Create a selector and start searching from the Root of AD $selector = New-Object DirectoryServices.DirectorySearcher $selector.SearchRoot = $root $adobj= $selector.findall() |` where {$_.properties.objectcategory -match « CN=computer »} foreach ($person in $adobj){ $prop=$person.properties $i++ Write-host « Le poste $args est membre de $($prop.memberof) »} } ListmemberOf ComputerName Liste des membres d’une OU: function ListOUCNMemberOf { $strFilter = « (&(objectCategory=computer)) » $objDomain = New-Object System.DirectoryServices.DirectoryEntry(« LDAP://OU=$args,dc=xxxx,dc=zzzz ») $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter $objSearcher.SearchScope = « OneLevel » $colProplist = « name » foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)} $colResults = $objSearcher.FindAll() foreach ($objResult in $colResults) {$objItem = $objResult.Properties; $objItem.name} } ListOUCNMemberOf Serveurs Recherhce d’un objet spécifique: Function SearchObject { param([string]$arg1, [string]$arg2) $searcher = New-Object DirectoryServices.DirectorySearcher([ADSI] » ») $searcher.filter = « (&(objectClass=$arg2)(sAMAccountName= $arg1)) » $searcher.findall() } SearchObject NOM_USER user Enjoy !!
Read More