Concept : La domande più frequenti su PowerShell.
È possibile utilizzare questo elenco in diversi modi :
- Per copiare / incollare i comandi in uno script
- Per vedere rapidamente la sintassi di un comando specifico
- Per migliorare la vostra conoscenza tecnica
- Per scoprire nuovi comandi
- Per preparare un colloquio di lavoro
Aggiornato |
7 ottobre 2015
|
Autore | powershell-guru.com |
Fonte | italian.powershell-guru.com |
Categorie |
75
|
Domande |
610
|
System
Come determinare la mia versione di PowerShell?
1 2 3 4 5 6 7 8 9 |
# via Powershell $PSVersionTable.PSVersion.Major # via Registry (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine').PowerShellVersion # Versions 1 and 2 (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine').PowerShellVersion # Versions 3 and 4 # via Remote Invoke-Command -ComputerName $computer -ScriptBlock { $PSVersionTable.PSVersion.Major } |
Come eseguire PowerShell in un’altra versione per renderlo compatibile con le versioni precedenti?
powershell.exe -Version 2.0
Come richiedere una versione minimale PowerShell (3.0 e superiori) in uno script con PowerShell?
#Requires -Version 3.0
Come richiedere privilegi amministrativi per uno script con Powershell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Come controllare i parametri di uno script con PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Come ottenere informazioni per l’utente corrente con Powershell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Come creare, modificare e caricare un profilo con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Check if a profile exists Test-Path -Path $PROFILE # Current User,Current Host Test-Path -Path $PROFILE.CurrentUserCurrentHost # Current User,Current Host Test-Path -Path $PROFILE.CurrentUserAllHosts # Current User,All Hosts Test-Path -Path $PROFILE.AllUsersCurrentHost # All Users, Current Host Test-Path -Path $PROFILE.AllUsersAllHosts # All Users, All Hosts # Create a new profile for current user New-Item -ItemType File -Force $PROFILE # CurrentUserCurrentHost New-Item -ItemType File -Force $PROFILE.CurrentUserCurrentHost New-Item -ItemType File -Force $PROFILE.CurrentUserAllHosts # Edit psEdit $PROFILE (only for ISE) ise $PROFILE (only for ISE) notepad.exe $PROFILE # Reload (without restarting Powershell) & $PROFILE .$PROFILE # List profiles $PROFILE | Format-List * -Force |
Come fare una pausa di 5 secondi / minuti in uno script con PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Come ottenere la data dell’ultimo accesso di Powershell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Come ottenere i type accelerators con Powershell?
1 |
[PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get.GetEnumerator() | Select-Object -Property @{Name='Key'; Expression={$_.Key}},@{name='Value'; Expression={$_.Value}} | Sort-Object -Property Key | Format-Table -AutoSize |
Come elencare i programmi di avvio con PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Come disinstallare un’applicazione con PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Come scattare uno screenshot del desktop o di una finestra attiva con Powershell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Come ottenere il numero di messaggi delle code MSMQ con PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Come impostare i criteri di esecuzione con Powershell?
1 2 3 4 5 6 7 8 9 10 11 |
# Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode. Set-ExecutionPolicy -ExecutionPolicy Restricted # AllSigned - Only scripts signed by a trusted publisher can be run. Set-ExecutionPolicy -ExecutionPolicy AllSigned # RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run. Set-ExecutionPolicy -ExecutionPolicy RemoteSigned # Unrestricted - No restrictions - All Windows PowerShell scripts can be run. Set-ExecutionPolicy -ExecutionPolicy Unrestricted |
Come creare una scorciatoia da tastiera con PowerShell?
1 2 3 4 |
$shell = New-Object -ComObject WScript.Shell $shortcut = $shell.Createshortcut("$HOME\Desktop\Procexp.lnk") $shortcut.TargetPath = 'C:\SysinternalsSuite\procexp.exe' $shortcut.Save() |
Come bloccare o sbloccare un programma dalla barra delle applicazioni con Powershell?
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
Come aprire una finestra di Explorer con PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Come elencare i driver di periferica con PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Come creare un GUID con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Empty GUID [GUID]::Empty 00000000-0000-0000-0000-000000000000 # New GUID (lower case by default) [GUID]::NewGuid() 7049b4a9-e4bc-4008-a683-067934bd39cf # New GUID (upper case) $guid = ([GUID]::NewGuid()).ToString().ToUpper() DD7F5A7B-F46B-49D0-B8A1-D8D1360D2E27 # New GUID with a specific value [GUID]('bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7') bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7 # New GUID (Powershell v5) New-Guid cdcaa4d9-c85f-40d7-afd9-32f003afa130 |
Come ottenere il percorso della directory temporanea per l’utente corrente con Powershell?
[System.IO.Path]::GetTempPath()
Come unire un percorso ed un sotto-percorso in un unico percorso con PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Come elencare tutti i cmdlet “Get- *” con Powershell?
Get-Command -Verb Get
Come elencare le cartelle di sistema speciali con PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Come montare i file / VHD ISO con Powershell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Come controllare le versioni installate di .NET Framework con Powershell?
1 |
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version -EA 0 | Where-Object -FilterScript { $_.PSChildName -match '^(?!S)\p{L}' } | Select-Object -Property PSChildName, Version |
Come controllare se la versione di .NET Framework 4.5 è installata con Powershell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Come avviare e fermare una trascrizione (per memorizzare la sessione di Windows PowerShell) con Powershell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Come cambiare la directory corrente in una posizione specifica con Powershell?
Set-Location -Path 'C:\scripts'
Come cancellare lo schermo con Powershell?
Clear-Host
cls # Alias
Come modificare la risoluzione dello schermo con Powershell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Come impostare la finestra a tutto schermo con Powershell?
mode.com 300
Come ottenere le dimensioni (larghezza e altezza) di una foto con Powershell?
1 2 3 4 5 6 7 |
$picture = New-Object -ComObject Wia.ImageFile $picture.LoadFile('C:\screenshot.jpg') [PSCustomObject] @{ Width = $picture.Width Height = $picture.Height } |
Come ottenere il codice Product Key di Windows con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function Get-WindowsKey { ## function to retrieve the Windows Product Key from any PC ## by Jakob Bindslet (jakob@bindslet.dk) param ($targets = '.') $hklm = 2147483650 $regPath = 'Software\Microsoft\Windows NT\CurrentVersion' $regValue = 'DigitalProductId' Foreach ($target in $targets) { $productKey = $null $win32os = $null $wmi = [WMIClass]"\\$target\root\default:stdRegProv" $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue) $binArray = ($data.uValue)[52..66] $charsArray = 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9' ## decrypt base24 encoded binary data For ($i = 24; $i -ge 0; $i--) { $k = 0 For ($j = 14; $j -ge 0; $j--) { $k = $k * 256 -bxor $binArray[$j] $binArray[$j] = [math]::truncate($k / 24) $k = $k % 24 } $productKey = $charsArray[$k] + $productKey If (($i % 5 -eq 0) -and ($i -ne 0)) { $productKey = '-' + $productKey } } $win32os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $target $obj = New-Object -TypeName Object $obj | Add-Member -MemberType Noteproperty -Name Computer -Value $target $obj | Add-Member -MemberType Noteproperty -Name Caption -Value $win32os.Caption $obj | Add-Member -MemberType Noteproperty -Name CSDVersion -Value $win32os.CSDVersion $obj | Add-Member -MemberType Noteproperty -Name OSArch -Value $win32os.OSArchitecture $obj | Add-Member -MemberType Noteproperty -Name BuildNumber -Value $win32os.BuildNumber $obj | Add-Member -MemberType Noteproperty -Name RegisteredTo -Value $win32os.RegisteredUser $obj | Add-Member -MemberType Noteproperty -Name ProductID -Value $win32os.SerialNumber $obj | Add-Member -MemberType Noteproperty -Name ProductKey -Value $productKey $obj } } |
Perfmon
Come ottenere il valore attuale del “% Tempo del processore” (media) degli ultimi 5 secondi (10 volte) con PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Come caricare insiemi con PowerShell?
1 2 3 4 5 6 |
Add-Type -AssemblyName 'System.Windows.Forms' Add-Type -Path 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll' # Deprecated [System.Reflection.Assembly]::LoadFrom('C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll') |
Come controllare gli insiemi .NET attuali caricati con Powershell?
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
Come trovare il percorso GAC (Global Assembly Cache) con Powershell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Come copiare i risultati negli appunti con PowerShell?
1 |
Get-Process | clip.exe |
Come ottenere il contenuto della clipboard con Powershell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Come ottenere gli aggiornamenti rapidi installati con Powershell?
Get-HotFix -ComputerName $computer
Come ottenere gli aggiornamenti rapidi installati prima / dopo una data specifica con Powershell?
Get-HotFix | Where-Object -FilterScript { $_.InstalledOn -lt ([DateTime]'01/01/2015') } # Before 01/01/2015
Get-HotFix | Where-Object -FilterScript {$_.InstalledOn -gt ([DateTime]'01/01/2015')} # After 01/01/2015
Come controllare se un aggiornamento è installato con Powershell?
Get-HotFix -Id KB2965142
Come ottenere gli aggiornamenti installati su un computer remoto con Powershell?
Get-HotFix -ComputerName $computer
Pagefile
Come ottenere informazioni sul file di Paging con Powershell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Come ottenere la dimensione consigliata (MB) per il file di Paging con Powershell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Come creare un file di paging (4096 MB) nell’unità D: con Powershell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Come cancellare un file di paging nell’unità C: con Powershell?
1 2 3 4 5 |
$privileges = Get-WmiObject -Class Win32_computersystem -EnableAllPrivileges $privileges.AutomaticManagedPagefile = $false $privileges.Put() $pagefile = Get-WmiObject -Query "select * from Win32_PageFileSetting where name='c:\\pagefile.sys'" $pagefile.Delete() # Reboot required |
Maintenance
Come controllare la frammentazione di un disco con PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Come controllare lo spazio delle unità sul disco con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Get-WmiObject -Class Win32_logicaldisk | Format-Table -Property @{ Name = 'Drive' Expression = {$_.DeviceID} }, @{ Name = 'Total size (GB)' Expression = {[decimal]('{0:N0}' -f($_.Size/1gb))} }, @{ Name = 'Free space(GB)' Expression = {[decimal]('{0:N0}'-f($_.Freespace/1gb))} }, @{ Name = 'Free (%)' Expression = {'{0,6:P0}' -f(($_.Freespace/1gb) / ($_.size/1gb))} } -AutoSize |
Files
Come aprire un file con PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Come leggere un file con PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Come scrivere l’output di un file con PowerShell?
1 2 3 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt' -Encoding ascii 'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt 'Line1', 'Line2', 'Line3' > file.txt |
Come ottenere il nome completo del file di script corrente con Powershell?
$MyInvocation.MyCommand.Path
Come decomprimere / zippare i file con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
### COMPRESS ONE FILE ### # Powershell v5 Compress-Archive -Path $fileSource -DestinationPath $fileDestination ### COMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::CreateFromDirectory($folderSource,$fileDestination) # Powershell v5 Compress-Archive -Path $folderSource -DestinationPath $fileDestination |
Come decomprimere / estrarre i file con PowerShell?
1 2 3 4 5 6 7 8 9 10 |
### UNCOMPRESS ONE FILE ### # Powershell v5 Expand-Archive -Path $fileSource -DestinationPath $folderDestination ### UNCOMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::ExtractToDirectory($fileSource, $folderDestination) |
Come visualizzare i file in un archivio ZIP con Powershell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Come visualizzare le dimensioni di un file in KB con Powershell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Come trovare i file superiori o inferiori ad 1 GB con Powershell?
1 2 3 4 5 |
# Larger than 1 GB Get-ChildItem -Path C:\ -Recurse -ErrorVariable $errorsSearch | Where-Object -FilterScript {$_.Length -gt 1GB} # Less than 1 GB Get-ChildItem -Path C:\ -Recurse -ErrorVariable $errorsSearch | Where-Object -FilterScript {$_.Length -lt 1GB} |
Come visualizzare il nome di un file senza estensione con Powershell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Come visualizzare l’estensione di un file con PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Come ottenere la versione di un file con PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Come ottenere l’hash di un file Powershell?
(Get-FileHash $file).Hash
Come ottenere il checksum MD5 / SHA1 di un file con PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Come visualizzare i file nascosti con Powershell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Come verificare se un file ha un’estensione con Powershell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Come impostare un file come file di sola lettura con Powershell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Come modificare l’attributo LastWriteTime alla settimana scorsa per un file con PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Come creare un nuovo file con Powershell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Come rinominare un file con Powershell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Come rinominare (bulk / batch) file multipli in con Powershell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Come cancellare un file con PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
Come visualizzare le ultime 10 righe di un file con Powershell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Come sbloccare i diversi file di una cartella con PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Come rimuovere le righe vuote da un file con Powershell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Come verificare l’esistenza di un file con Powershell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Come ottenere il file più recente / antico creato in una cartella con PowerShell?
1 2 |
Get-ChildItem | Sort-Object -Property CreationTime | Select-Object -Last 1 # Newest Get-ChildItem | Sort-Object -Property CreationTime | Select-Object -First 1 # Oldest |
Come rimuovere le righe doppie da un file con Powershell?
1 2 |
Get-Content -Path .\file.txt | Select-Object -Unique # Display Get-Content -Path .\file.txt | Select-Object -Unique | Set-Content -Path .\testing.txt # Save |
Come ottenere i file creati in una cartella da più / meno di 1 mese con Powershell?
1 2 3 |
$1MonthAgo = (Get-Date).AddMonths(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
Come ottenere i file creati in una cartella da più / meno di 1 anno con PowerShell?
1 2 3 |
$1YearAgo = (Get-Date).AddYears(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1YearAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1YearAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
Come esportare il valore di una variabile in un file con PowerShell?
Set-Content -Path file.txt -Value $variable
Come contare il numero di file (* .txt) in una cartella con PowerShell?
1 2 3 |
[System.IO.Directory]::GetFiles('C:\scripts', '*.txt').Count (Get-ChildItem -Path 'C:\scripts' -Filter *.txt).Count (Get-ChildItem -Path 'C:\scripts' -Filter *.txt -Recurse).Count # Recursive |
Come cercare una stringa all’interno di file multipli con PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Come visualizzare la prima / ultima riga di un file con PowerShell?
1 2 3 4 5 6 7 8 9 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt # First Line Get-Content -Path .\file.txt | Select-Object -First 1 # Returns Line1 (Get-Content -Path .\file.txt)[0] # Returns Line1 # Last Line Get-Content -Path .\file.txt | Select-Object -Last 1 # Returns Line3 (Get-Content -Path .\file.txt)[-1] # Returns Line3 |
Come visualizzare uno specifico numero di riga di un file con PowerShell?
1 2 3 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt Get-Content -Path .\file.txt | Select-Object -Index 0 # Returns Line1 Get-Content -Path .\file.txt | Select-Object -Index 2 # Returns Line3 |
Come contare il numero di righe di un file con PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Come contare il numero di caratteri e di parole di un file con PowerShell?
1 2 3 4 5 6 7 8 9 10 |
'Test', 'Powershell', 'Test Powershell' | Out-File -FilePath file.txt # Words (Return 4) (Get-Content -Path .\file.txt | Measure-Object -Word).Words # Characters (Return 23) (Get-Content -Path .\file.txt | Measure-Object -Character).Characters # Characters and ignore whitespaces (Return 22) (Get-Content -Path .\file.txt | Measure-Object -Character -IgnoreWhiteSpace).Characters |
Come scaricare un file con Powershell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Come visualizzare il percorso completo di un file con Powershell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Come copiare un file in una cartella con PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Come copiare un file in più cartelle con PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Come copiare più file in una cartella con PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Come trovare i server del catalogo globale su Active Directory con PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Come trovare siti su Active Directory con PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Come trovare il controller di dominio attuale con Powershell?
1 2 3 4 5 6 7 8 9 10 |
(Get-ADDomainController).HostName # Solution 1 $env:LOGONSERVER # Solution 2 [System.Environment]::GetEnvironmentVariable('logonserver') # Solution 3 nltest.exe /dsgetdc:domain.com |
Come trovare il controller di dominio completo in un dominio con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 (Get-ADDomainController -Filter *).Name # Solution 2 (Get-ADGroupMember 'Domain Controllers').Name # Solution 3 ((Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))')).Name # Solution 4 ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).DomainControllers.Name |
Come trovare i fallimenti di replica AD con PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
Come trovare la durata di rimozione per la foresta su Active Directory con Powershell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Come ottenere i dettagli di una foresta / dominio su Active Directory con Powershell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Come ottenere il percorso del contenitore “Oggetti eliminati” su Active Directory con Powershell?
(Get-ADDomain).DeletedObjectsContainer
Come abilitare la funzione Cestino AD su Active Directory con Powershell?
1 |
Enable-ADOptionalFeature -Identity 'CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=domain,DC=com' -Scope ForestOrConfigurationSet -Target 'domain.com' |
Come ripristinare un account AD dal Cestino su Active Directory con Powershell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Come trovare i ruoli di FSMO con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 Get-ADForest | Format-List -Property SchemaMaster, DomainNamingMaster Get-ADDomain | Format-List -Property PDCEmulator, RIDMaster, InfrastructureMaster # Solution 2 netdom query fsmo # Solution 3 [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().SchemaRoleOwner [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().NamingRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().InfrastructureRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().RidRoleOwner |
Come connettersi ad uno specifico controller di dominio con Powershell?
Get-ADUser -Identity $user -Server 'serverDC01'
Come ottenere il server di accesso corrente con Powershell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Come eseguire “gpupdate” su un computer con PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Come creare un nuovo gruppo su Active Directory con Powershell?
1 |
New-ADGroup -Name 'Powershell Guru' -SamAccountName powershellguru -GroupCategory Security -GroupScope Global -DisplayName 'Powershell Guru' -Path 'OU=MyOU,DC=domain,DC=com' -Description 'My account' |
Come rimuovere un gruppo su Active Directory con Powershell?
Remove-ADGroup -Identity 'PowershellGuru'
Come aggiungere un utente ad un gruppo su Active Directory con Powershell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Come rimuovere un utente da un gruppo su Active Directory con Powershell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Come trovare gruppi vuoti (senza componenti) su Active Directory con Powershell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Come contare i gruppi vuoti (senza componenti) su Active Directory con Powershell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Come ottenere i componenti di un gruppo su Active Directory con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Solution 1 (Get-ADGroupMember 'Powershell Guru').DistinguishedName (Get-ADGroupMember 'Powershell Guru').Samaccountname # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
Come ottenere i componenti di un gruppo con componenti ricorsivi su Active Directory con PowerShell?
1 2 |
(Get-ADGroupMember 'Powershell Guru' -Recursive).DistinguishedName (Get-ADGroupMember 'Powershell Guru' -Recursive).Samaccountname |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | Select-Object -ExpandProperty Samaccountname).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | Select-Object -ExpandProperty Samaccountname).Count |
Users
Come utilizzare un carattere jolly nel filtro di “Get-ADUser” su Active Directory con Powershell?
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
Come spostare un utente ad un’altra OU su Active Directory con Powershell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Come trovare tutti i “MemberOf” (Nested -annidati) di un utente con Powershell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Come ottenere il MemberOF (nome breve / troncato) di un utente con Powershell?
(Get-ADUser -Identity $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object
1 2 |
Set-ADUser $samAccountName -DisplayName 'DisplayName' -GivenName 'Test' -Surname 'Powershell' -DisplayName 'Test Powershell' Rename-ADObject $dn -NewName 'Test Powershell' #FullName |
Come modificare la Descrizione, l’Ufficio ed il numero di Telefono di un account utente su Active Directory con Powershell?
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'
1 2 3 4 5 |
# 31/12/2015 Set-ADAccountExpiration $samAccountName -DateTime '01/01/2016' # Never Clear-ADAccountExpiration $samAccountName |
Come sbloccare un account utente su Active Directory con Powershell?
Unlock-ADAccount $samAccountName
Come abilitare / disabilitare un account utente su Active Directory con Powershell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Come rimuovere un account utente su Active Directory con Powershell?
Remove-ADUser $samAccountName
Come reimpostare una password per un account utente su Active Directory con Powershell?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
Come reimpostare una password per diversi account utente (bulk) su Active Directory con PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
Come trovare il proprietario di un file su Active Directory con Powershell?
1 2 3 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList (Get-Acl -Path 'userFile.txt').Owner $sid = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value Get-ADUser $sid |
Come trovare l’ OU (Unità organizzativa) per un utente su Active Directory con Powershell?—
[regex]::match("$((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Come trovare account utenti disabilitati su Active Directory con PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Come trovare account scaduti di utenti su Active Directory con PowerShell?
Search-ADAccount -AccountExpired
Come trovare account bloccati di utenti su Active Directory con PowerShell?
Search-ADAccount -LockedOut
Come trovare il SID di un account utente su Active Directory con Powershell?
(Get-ADUser -Identity $user -Properties SID).SID.Value
Come convertire un nome utente in SID su Active Directory con Powershell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Come convertire un SID in un nome utente su Active Directory con Powershell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
Come dividere il Nome Distintivo di un account utente con Active Directory con Powershell?
1 2 3 |
$dn = 'CN=Powershell Test,OU=TEST,DC=domain,DC=com' $dn.Split(',')[0] # Returns "CN=Powershell Test" $dn.Split(',')[0].Split('=')[1] # Returns "Powershell Test" |
Come trovare la data di creazione / modifica di un account utente con Active Directory con Powershell?
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated
1 2 3 |
$schema = [DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema() $schema.FindClass('user').mandatoryproperties | Format-Table $schema.FindClass('user').optionalproperties | Format-Table |
Come ottenere il percorso LDAP di un utente su Active Directory con Powershell?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
Come cambiare il CN (Nome Canonico) di un utente su Active Directory con Powershell?
Rename-ADObject $((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Come ottenere l’Unità Organizzativa (OU) madre di un utente su Active Directory con Powershell?
1 2 |
$dn = (Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
1 2 |
$dn = (Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Come convertire l’attributo pwdLastSet di un utente su Active Directory con Powershell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Come verificare il canale protetto tra il computer locale e il dominio con Powershell?
Test-ComputerSecureChannel
Come riparare il canale protetto tra il computer locale e il dominio con Powershell?
Test-ComputerSecureChannel -Repair
Come disattivare un account computer su Active Directory con Powershell?
Disable-ADAccount $computer
Come trovare i computer con Sistema Operativo Specifico su Active Directory con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Get-ADComputer -Filter 'OperatingSystem -eq "CentOS"' Get-ADComputer -Filter 'OperatingSystem -eq "GNU/Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Mac OS X"' Get-ADComputer -Filter 'OperatingSystem -eq "OnTap"' Get-ADComputer -Filter 'OperatingSystem -eq "Red Hat Enterprise Linux Server"' Get-ADComputer -Filter 'OperatingSystem -eq "redhat-linux-gnu"' Get-ADComputer -Filter 'OperatingSystem -eq "Samba"' Get-ADComputer -Filter 'OperatingSystem -eq "Ubuntu"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows NT"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Server"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows XP Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2003"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Business"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Entreprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Ultimate"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server® 2008 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8.1 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 Standard"' |
Organizational Unit (OU)
Come creare un’unità organizzativa (OU) su Active Directory con Powershell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Come ottenere i dettagli di un’unità organizzativa (OU) su Active Directory con Powershell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Come modificare la descrizione di un’unità organizzativa (OU) su Active Directory con Powershell?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
1 2 3 4 5 |
# Protection ON Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $true # Protection OFF Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false |
1 |
Get-ADOrganizationalUnit -Filter * -Property ProtectedFromAccidentalDeletion | Where-Object -FilterScript { $_.ProtectedFromAccidentalDeletion -eq $false } | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true |
1 2 |
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false Remove-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' |
1 2 |
$parent = $dn.Split(',',2)[1] $parent = (Get-ADOrganizationalUnit $parent -Properties CanonicalName).CanonicalName |
Come elencare le unità organizzative vuote (OU) con PowerShell?
1 2 3 4 5 |
# Solution 1 Get-ADOrganizationalUnit -Filter * -Property 'msDS-Approx-Immed-Subordinates' | Where-Object -FilterScript {$_.'msDS-Approx-Immed-Subordinates' -eq 0} # Solution 2 ([adsisearcher]'(objectclass=organizationalunit)').FindAll() | Where-Object -FilterScript { (([adsi]$_.Path).PSbase.Children | Measure-Object).Count -eq 0 } |
Come ottenere il manager di un gruppo con PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Come estrarre un indirizzo IP v4 (80.80.228.8) con la Regex con Powershell?
$example = 'The IP address is 80.80.228.8'
$ip = [regex]::match($example,'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').value
Come estrarre un indirizzo MAC (C0-D9-62-39-61-2D) con separatore “-” con la Regex con Powershell?
$example = 'The MAC address is C0-D9-62-39-61-2D'
$mac = [regex]::match($example,'([0-9A-F]{2}[-]){5}([0-9A-F]{2})').value
Come estrarre un indirizzo MAC (C0: D9: 62: 39: 61: 2D) con separatore “:” con la Regex con Powershell?
$example = 'The MAC address is C0:D9:62:39:61:2D'
$mac = [regex]::match($example,'((\d|([a-f]|[A-F])){2}:){5}(\d|([a-f]|[A-F])){2}').value
Come estrarre una data (10/02/2015) con la Regex con Powershell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Come estrarre un URL (www.powershell-guru.com) con la Regex con Powershell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Come estrarre una e-mail (utente@dominio.com) con le Regex con Powershell?
$example = 'The email is user@domain.com'
$email = [regex]::match($example,'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b').value
Come estrarre “guru” da una stringa campione con la Regex con Powershell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Come estrarre “guru.com” da una stringa campione con la Regex con Powershell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Come estrarre “powershell-guru.com” da una stringa campione con la Regex con Powershell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Come estrarre “123” dalla stringa campione con la Regex con Powershell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Come estrarre “$” (simbolo del dollaro) dalla riga campione con la Regex con Powershell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Come sostituire un carattere (* .com) con un altro (* .fr) in una stringa con la Regex con Powershell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Come effetturare l’escape di una stringa con la Regex con Powershell?
[regex]::Escape('\\server\share')
Memory
Come gestire la memoria forzando una garbage collection con Powershell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Come ottenere la dimensione della RAM di un computer con PowerShell?
1 2 3 4 5 6 7 8 |
# Solution 1 Get-CimInstance -ClassName 'cim_physicalmemory' | ForEach-Object -Process {$_.Capacity /1GB} # Solution 2 (Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory /1GB # Solution 3 (systeminfo.exe | Select-String -Pattern 'Total Physical Memory:').ToString().Split(':')[1].Trim() |
Date
Come ottenere la data corrente con Powershell?
Get-Date
[Datetime]::Now
Come visualizzare la data in diversi formati con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
### DATETIME ### Get-Date -Format D : Tuesday, June 30, 2015 Get-Date -Format f : Tuesday, June 30, 2015 3:22 PM Get-Date -Format F : Tuesday, June 30, 2015 3:22:58 PM Get-Date -Format g : 6/30/2015 3:23 PM Get-Date -Format G : 6/30/2015 3:23:30 PM Get-Date -DisplayHint Date : Tuesday, June 30, 2015 Get-Date -DisplayHint DateTime : Tuesday, June 30, 2015 3:31:21 PM ### DATE ### Get-Date -Format d : 6/30/2015 Get-Date -Format yyyyMMdd : 20150630 Get-Date -UFormat '%d%m%Y' : 30062015 Get-Date -UFormat '%m%d%Y' : 06302015 Get-Date -UFormat '%Y%m%d' : 20150630 Get-Date -UFormat '%d.%m.%Y' : 30.06.2015 Get-Date -UFormat '%m.%d.%Y' : 06.30.2015 Get-Date -UFormat '%Y.%m.%d' : 2015.06.30 Get-Date -UFormat '%d-%m-%Y' : 30-06-2015 Get-Date -UFormat '%m-%d-%Y' : 06-30-2015 Get-Date -UFormat '%Y-%m-%d' : 2015-06-30 Get-Date -UFormat '%d/%m/%Y' : 30/06/2015 Get-Date -UFormat '%m/%d/%Y' : 06/30/2015 Get-Date -UFormat '%Y/%m/%d' : 2015/06/30 ### HOUR ### Get-Date -Format t : 3:23 PM Get-Date -Format T : 3:23:30 PM Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 28 (Minute) Get-Date -Format ss : 30 (Seconds) Get-Date -DisplayHint Time : 3:23:30 PM ### DAY ### Get-Date -Format dddd : Tuesday Get-Date -Format ddd : Tue Get-Date -Format dd : 30 ### MONTH ### Get-Date -Format MMMM : June Get-Date -Format MMM : Jun Get-Date -Format MM : 06 ### YEAR ### Get-Date -Format yyyy : 2015 |
Come convertire un oggetto (DateTime) in una data (Stringa) con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 $datetimeToString = '{0:MM/dd/yy}' -f (Get-Date '07/15/2015') # Solution 2 $datetimeToString = (Get-Date '07/15/2015').ToShortDateString() # Check $datetimeToString 07/15/15 $datetimeToString.GetType().Name String |
Come convertire una data (stringa) in un oggetto (DateTime) con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Solution 1 $stringToDatetime = '07/15/2015' | Get-Date $stringToDatetime = '07-15-2015' | Get-Date # Solution 2 [Datetime]::ParseExact('07/15/2015', 'MM/dd/yyyy', $null) # Solution 3 $stringToDatetime = [Datetime]'7/15/2015' # Check $stringToDatetime Wednesday, July 15, 2015 12:00:00 AM $stringToDatetime.GetType().Name Datetime |
Come calcolare la differenza (numero di giorni, ore, minuti o secondi) tra due date con PowerShell?
(New-TimeSpan -Start $dateStart -End $dateEnd).Days
(New-TimeSpan -Start $dateStart -End $dateEnd).Hours
(New-TimeSpan -Start $dateStart -End $dateEnd).Minutes
(New-TimeSpan -Start $dateStart -End $dateEnd).Seconds
Come confrontare due date con Powershell?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False
Come ordinare una serie di date come Datetime con Powershell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Come avviare e arrestare un cronometro con PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Come ottenere il giorno corrente della settimana con Powershell?
(Get-Date).DayOfWeek #Sunday
Come ottenere la data di ieri con Powershell?
(Get-Date).AddDays(-1)
Come ottenere il numero dei giorni di un mese (Febbraio 2015) con Powershell?
[DateTime]::DaysInMonth(2015, 2)
Come determinare se un anno è bisestile con Powershell?
[DateTime]::IsLeapYear(2015)
Come elencare i fusi orari con PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Come codificare (in formato ASCII) e decodificare un URL con PowerShell?
1 2 3 4 5 6 7 8 9 |
# Encode $url = 'http://www.powershell-guru.com' $encoded = [System.Web.HttpUtility]::UrlEncode($url) # Decode $decoded = [System.Web.HttpUtility]::UrlDecode($encoded) # Encoded : http%3a%2f%2fwww.powershell-guru.com # Decoded : http://www.powershell-guru.com |
Quali sono gli equivalenti dei comandi di rete nativi con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# ipconfig Get-NetIPConfiguration Get-NetIPAddress # ping Test-NetConnection # tracert Test-NetConnection -TraceRoute # route Get-NetRoute # nslookup Resolve-DnsName # Windows 8.1 & Windows 2012 ([System.Net.Dns]::GetHostEntry($IP)).Hostname # IP > PC ([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString # PC > IP |
Come ottenere gli indirizzi IP con Powershell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Come disattivare indirizzo IP v6 (IPv6) con Powershell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Come convalidare un indirizzo IP v4 (IPv4) con Powershell?
if([ipaddress]'10.0.0.1'){'validated'}
Come trovare l’indirizzo IP esterno con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Solution 1 (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content (iwr -Uri 'myexternalip.com/raw').Content # Alias # Solution 2 $webClient = New-Object -TypeName System.Net.WebClient $webClient.DownloadString('http://myexternalip.com/raw') # Solution 3 while ($true) { Write-Output -InputObject "$(Get-Date) - $((Invoke-WebRequest -Uri 'http://myexternalip.com/raw' -Method Get).Content)" Start-Sleep -Seconds 300 } |
Come trovare il nome host da un indirizzo IP con Powershell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Come trovare l’indirizzo IP da un nome host con PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Come trovare il dominio FQDN da un nome host con PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
Come trovare la configurazione di rete (IP, Subnet, Gateway e DNS) con Powershell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Come trovare l’indirizzo MAC con Powershell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Come esegure un ping con PowerShell?
1 2 3 4 5 6 |
# Solution 1 Test-Connection -ComputerName $computer -Quiet # Returns True / False # Solution 2 $ping = New-Object -TypeName System.Net.Networkinformation.Ping $ping.Send($computer) |
Come verificare se un computer è connesso ad Internet con PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Come eseguire una ricerca whois per un sito web con PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Come ottenere i dettagli di un IP pubblico (Geolocation) con Powershell?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Come controllare se una porta è aperta / chiusa con Powershell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Come effettuare un tracert con Powershell?
Test-NetConnection www.google.com -TraceRoute
Come correggere un profilo di una connesione domestica con Powershell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Come mostrare le connessioni delle porte TCP con PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Come accorciare un URL lungo in un URL breve con Powershell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Come ottenere le impostazioni proxy con Powershell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Come controllare la cache DNS sul computer locale con Powershell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Come cancellare la cache DNS sul computer locale con Powershell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Come cancellare la cache DNS su computer remoti con PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Come leggere il file Hosts con Powershell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Come generare una password casuale con Powershell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Come modificare la password di un account amministratore sul server remoto con Powershell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Come trovare la data di scadenza della password di un account in Active Directory con Powershell?
1 2 3 4 5 6 7 8 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed').'msDS-UserPasswordExpiryTimeComputed') # Solution 2 Get-Date -Date ((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
Come elencare tutte le stampanti per un server specifico con Powershell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Come elencare tutte le porte per un server specifico con Powershell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Come cambiare la notifica / posizione di una stampante con PowerShell?
1 2 3 4 |
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'" $printer.Location = 'Germany' $printer.Comment = 'Printer - Test' $printer.Put() |
Come eliminare (annullare) tutti i processi di una stampante con PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Come stampare una pagina di prova di una stampante con PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Come ottenere le code di stampa delle stampanti con PowerShell?
1 2 3 4 |
Get-WmiObject -Class Win32_PerfFormattedData_Spooler_PrintQueue | Select-Object -Property Name, @{ Expression = {$_.jobs} Label = 'Current Jobs' } | Format-Table -AutoSize |
Regedit
Read
Come ottenere l’elenco di hives del Registro con PowerShell?
Get-ChildItem -Path Registry::
Come ottenere i valori del Registro di sistema ed i tipi di valore con Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function Get-RegistryValue { Param ( [Parameter(Mandatory = $true)] [string]$RegistryKey ) $key = Get-Item -Path "Registry::$RegistryKey" $key.GetValueNames() | Sort-Object | ForEach-Object -Process { $name = $_ $type = $key.GetValueKind($name) switch ($type) { 'String' {'REG_SZ'} 'Binary' {'REG_BINARY'} 'Dword' {'REG_DWORD'} 'Qword' {'REG_QWORD'} 'MultiString' {'REG_MULTI_SZ'} 'ExpandString'{'REG_EXPAND_SZ'} Default {$null} } [PSCustomObject]@{ Name = $name Type = $type Data = $key.GetValue($name) } } } |
Come ottenere l’elenco di chiavi e sottochiavi del Registro con PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#HKEY_CLASSES_ROOT New-PSDrive -PSProvider Registry -Root HKEY_CLASSES_ROOT -Name HKCR Get-ChildItem -Path 'HKCR:\' #HKEY_CURRENT_USER Get-ChildItem -Path 'HKCU:\Software' Get-ChildItem -Path Registry::HKEY_CURRENT_USER #HKEY_LOCAL_MACHINE Get-ChildItem -Path 'HKLM:\SYSTEM' Get-ChildItem -Path Registry::HKEY_LOCAL_MACHINE #HKEY_USERS New-PSDrive -PSProvider Registry -Root HKEY_USERS -Name HKU Get-ChildItem -Path 'HKU:\' #HKEY_CURRENT_CONFIG New-PSDrive -PSProvider Registry -Root HKEY_CURRENT_CONFIG -Name HKCC Get-ChildItem -Path 'HKCC:\' |
Come ottenere l’elenco di chiavi e sottochiavi in modo ricorsivo con Powershell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Come trovare le sottochiavi con un nome specifico con Powershell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Come ottenere solo il nome delle sottochiavi del registro con PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Come ottenere l’elenco dei valori del Registro di PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Come leggere un valore specifico del Registro con Powershell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Come leggere un valore specifico del registro su computer remoto con Powershell?
1 2 3 4 5 |
$hostname = $computer $openRegedit = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $hostname) $openKey = $openRegedit.OpenSubKey('SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion') $keyValue = $openKey.GetValue('ProductName') $keyValue |
Write
Come creare una nuova chiave di registro con Powershell?
New-Item -Path 'HKCU:\Software\MyApplication'
Come creare un valore del Registro con Powershell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Come modificare un valore di registro esistente con Powershell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Come cancellare un valore di Registro di sistema con Powershell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Come eliminare una chiave di registro con Powershell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Come verificare se una chiave di registro esiste con Powershell?
Test-Path -Path 'HKCU:\Software\MyApplication'
Come verificare se un valore di registro esiste con Powershell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Come rimuovere gli spazi vuoti all’inizio di una stringa con Powershell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Come rimuovere gli spazi vuoti alla fine di una stringa con PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Come rimuovere gli spazi vuoti (all’inizio ed alla fine fine) di una stringa con Powershell?
$string = ' PowershellGuru '
$string = $string.Trim()
Come convertire una stringa in maiuscolo con Powershell?
$string = 'powershellguru'
$string = $string.ToUpper()
Come convertire una stringa in minuscolo con Powershell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Come selezionare la stringa “PowerShell” dalla stringa “PowershellGuru” con Powershell?
$string.Substring(0,10)
Come selezionare la stringa “Guru” dalla stringa “PowershellGuru” con Powershell?
$string.Substring(10)
Come selezionare il numero “123” di “Powershell123Guru” con Powershell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Come ottenere l’indice a base zero del “Guru” dalla stringa “PowershellGuru” con Powershell?
$string.IndexOf('Guru') # 10
Come controllare se una stringa è nulla o vuota con Powershell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Come verificare se una stringa sia nulla, vuota o formata da spazi vuoti con Powershell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Come controllare se una stringa contiene una lettera specifica con Powershell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Come riottenere la lunghezza di una stringa con Powershell?
$string.Length
Come concatenare due stringhe con PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Come evidenziare una o più parentesi quadre “[]” in una stringa con PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Come evidenziare una o più parentesi tonde “()” in una stringa con Powershell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Come evidenziare una o più parentesi graffe “{}” in una stringa con PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Come evidenziare una o più parentesi angolate “< >” in una stringa con PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Come evidenziare tutte le lettere minuscole (abc) in una stringa con PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Come evidenziare tutte le maiuscole (ABC) in una stringa con PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Come evidenziare la “[p” (p minuscola) in una stringa con Powershell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Come evidenziare la “[P” (P maiuscola) in una stringa con Powershell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Come sostituire una riga con un’altra con Powershell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Come convertire un’operazione di divisione in una stringa (Percentuale) con Powershell?
(1/2).ToString('P')
Come ordinare le stringhe contenenti i numeri con Powershell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Come selezionare l’ultima parola di una frase con PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Come ottenere la più grande parola di una frase con Powershell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Come contare il numero di volte che una stringa è presente all’interno di una frase con Powershell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Come copiare ogni carattere in una stringa in un array di caratteri con Powershell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Come convertire in maiuscolo la prima lettera di una stringa con PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Come aggiungere spazio (a sinistra o a destra) ad una stringa con PowerShell?
1 2 3 4 5 6 7 |
# With whitespaces $padRight = 'test'.PadRight(25) $padLeft = 'test'.PadLeft(25) # With characters $padRight = 'test'.PadRight(25,'.') # Return test.................... $padLeft = 'test'.PadLeft(25,'.') # Return ....................test |
Come codificare e decodificare una stringa Base64 con PowerShell?
1 2 3 4 5 6 7 8 9 10 |
# Encode $string = [System.Text.Encoding]::UTF8.GetBytes('test') $encoded = [System.Convert]::ToBase64String($string) # Decode $string = [System.Convert]::FromBase64String($encoded) $decoded = [System.Text.Encoding]::UTF8.GetString($string) # Encoded : c3RldmU= # Decoded : test |
Come convertire un numero da / a binario con Powershell?
1 2 3 4 5 |
# Base 10 to Base 2 [System.Convert]::ToString(255,2) # Base 2 to Base 10 [System.Convert]::ToInt32('11111111',2) |
Come ottenere solo l’ultima cartella madre di un percorso con PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Come ottenere solo l’ultimo elemento di un percorso con PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Come elencare i metodi della classe System.Math con Powershell?
[System.Math] | Get-Member -Static -MemberType Method
Come ottenere il valore assoluto con Powershell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Come ottenere l’angolo il cui seno è il numero specificato con Powershell?
[Math]::ASin(1) #Returns 1,5707963267949
Come ottenere la funzione ceiling con Powershell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Come ottenere la funzione floor con Powershell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Come ottenere il logaritmo naturale ( base e) di un numero specifico con Powershell?
[Math]::Log(4) #Returns 1,38629436111989
Come ottenere il logaritmo in base 10 di un numero specifico di PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
Come ottenere il massimo di due valori con Powershell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Come ottenere il minimo di due valori con Powershell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Come ottenere un numero elevato alla potenza specificata con Powershell?
[Math]::Pow(2,4) #Returns 16
Dato un valore decimale, come ottenere il valore integrale più vicino con Powershell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Come ottenere la parte integrale di un numero decimale specificato con Powershell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Come ottenere la radice quadrata di un numero specificato con Powershell?
[Math]::Sqrt(16) #Returns 4
Come ottenere la costante PI con Powershell?
[Math]::Pi #Returns 3,14159265358979
Come ottenere la base logaritmica naturale (costante e) con Powershell?
[Math]::E #Returns 2,71828182845905
Come verificare se un numero è pari o dispari con Powershell?
[bool]($number%2)
Hashtables
Come creare una tabella hash vuota con Powershell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Come creare una tabella hash con elementi con Powershell?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
Come aggiungere elementi (coppia chiave-valore) ad una tabella hash con Powershell?
$hashtable.Add('Key4', 'Value4')
Come ottenere un valore specifico di una tabella hash con PowerShell?
1 2 3 4 5 6 7 |
# Returns only Value $hashtable.Key1 $hashtable['Key1'] $hashtable.Item('Key1') # Returns Key and Value $hashtable.GetEnumerator() | Where-Object{$_.Name -eq 'Key1'} |
Come ottenere il valore minimo di una tabella hash con PowerShell?
1 2 3 4 5 6 7 8 |
$hashtable = @{ 'Key1' = '1' 'Key2' = '2' 'Key3' = '3' } $hashtable.GetEnumerator() | Sort-Object -Property Value | Select-Object -First 1 $hashtable.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -Last 1 |
Come ottenere il valore massimo di una tabella hash con PowerShell?
1 2 3 4 5 6 7 8 |
$hashtable = @{ 'Key1' = '1' 'Key2' = '2' 'Key3' = '3' } $hashtable.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -First 1 $hashtable.GetEnumerator() | Sort-Object -Property Value | Select-Object -Last 1 |
Come modificare gli elementi in una tabella hash con PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Come rimuovere gli elementi in una tabella hash con PowerShell?
$hashtable.Remove('Key1')
Come cancellare una tabella hash con PowerShell?
$hashtable.Clear()
Come controllare la presenza di una chiave/valore specifico in una tabella hash con PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Come ordinare per chiave/valore specifico una tabella hash con PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Come creare un array vuoto con Powershell?
$array = @()
$array = [System.Collections.ArrayList]@()
Come creare un array con elementi con Powershell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Come aggiungere elementi ad un array con Powershell?
$array += 'D'
[void]$array.Add('D')
Come modificare un elemento di un array con PowerShell?
$array[0] = 'Z' # 1st item[0]
Come controllare la dimensione di un array con Powershell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Come recuperare un oggetto / alcuni / tutti gli elementi di un array con Powershell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Come rimuovere gli elementi vuoti in un array con PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Come verificare l’esistenza di un elemento in un array con Powershell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Come trovare il numero di indice di un elemento in un array con PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Come invertire l’ordine degli elementi in un array con Powershell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Come generare un elemento casuale da un array con Powershell?
$array | Get-Random
Come ordinare un array in ordine crescente / decrescente con Powershell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Come contare il numero di elementi in un array con Powershell?
$array.Count
Come aggiungere un array ad un altro con PowerShell?
$array1 = 'A', 'B', 'C'