Concepte : Les preguntes més freqüents sobre PowerShell.
Podeu utilitzar aquesta llista de diferents maneres :
- Per copiar / enganxar comandaments en un script
- Per veure ràpidament la sintaxi d’una comanda específica
- Per millorar el seu coneixement tècnic
- Per descobrir nous ordres
- Per preparar una entrevista de treball
Actualitzat |
16 juliol 2015
|
Autor | powershell-guru.com |
Font | catalan.powershell-guru.com |
Categories |
75
|
Preguntes |
610
|
System
Com determinar la meva versió de 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 } |
Com executar PowerShell en una altra versió de compatibilitat amb versions anteriors?
powershell.exe -Version 2.0
Com requerir una versió PowerShell mínima (3.0 i superior) en un guió amb PowerShell?
#Requires -Version 3.0
Com requerir privilegis d’administració per a un guió amb PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Comprovar els paràmetres d’un guió amb PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Com obtenir informacions per a l’usuari actual amb PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Com crear, editar i tornar a carregar un perfil amb PowerShell?
1 2 3 4 5 6 7 8 9 10 |
# Create New-Item -Type file -Force $profile # Edit psEdit $profile ise $profile # Reload (without restarting Powershell) & $profile .$profile |
Com fer una pausa de 5 segons / minuts en un guió amb PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Com aconseguir l’última arrencada amb PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Com aconseguir diferents tipus d’acceleradors amb 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 |
Com llistar els programes d’inici amb PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Com desinstal·lar una aplicació amb PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Com prendre una captura de pantalla de tot l’escriptori o d’una finestra activa amb PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Com obtenir el nombre de missatges de cues MSMQ amb PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Com configurar la política d’execució de 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 |
Com crear un accés directe amb 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() |
Com fixar o alliberar un programa a la barra de tasques amb 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') |
Com obrir una finestra de Windows Explorer amb PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Com enumerar els controladors de dispositiu amb PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Com crear un GUID amb 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 |
Com obtenir la ubicació del directori temporal per a l’usuari actual amb PowerShell?
[System.IO.Path]::GetTempPath()
Com unir-se a un camí i una ruta secundària en un sol camí amb PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Com llistar tots els cmdlets “Obtenció *” amb PowerShell?
Get-Command -Verb Get
Com llistar carpetes especials del sistema amb PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Com muntar arxius / VHD ISO amb PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Com comprovar les versions de .NET Framework instal·lades amb 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 |
Com comprovar si la versió de .NET Framework 4.5 s’instal·la amb PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Com iniciar i aturar una transcripció (per crear un registre de la sessió del Windows PowerShell) amb PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Com canviar el directori actual a una ubicació específica amb PowerShell?
Set-Location -Path 'C:\scripts'
Com netejar la pantalla amb PowerShell?
Clear-Host
cls # Alias
Com canviar la resolució de pantalla amb PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Com configurar la finestra de pantalla completa amb PowerShell?
mode.com 300
Com obtenir les dimensions (amplada i alçada) d’una imatge amb 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 } |
Com obtenir la clau de producte de Windows amb 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
Com aconseguir l’actual “% temps de processador” (mitjana) en els últims 5 segons (10 vegades) amb PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Com carregar conjunts amb 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') |
Com comprovar els conjunts .NET actuals carregats amb 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*' } |
Com trobar la (memòria cau de acoblats global) Ruta GAC ??amb PowerShell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Com copiar els resultats al porta-retalls amb PowerShell?
1 |
Get-Process | clip.exe |
Com obtenir el contingut del portapapers amb PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Com obtenir les revisions instal·lades amb PowerShell?
Get-HotFix -ComputerName $computer
Com obtenir les revisions instal·lades abans / després d’una data específica amb 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
Com comprovar si una revisió s’instal·la amb PowerShell?
Get-HotFix -Id KB2965142
Com obtenir les revisions instal·lades en un equip remot amb PowerShell?
Get-HotFix -ComputerName $computer
Pagefile
Com obtenir les informacions PAGEFILE amb PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Com obtenir la mida recomanada (MB) per a l’arxiu de pàgina amb PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Com crear un arxiu de pàgina (4096 MB) en D: conduir amb PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Com esborrar un arxiu de pàgina en la unitat C: amb 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
Com comprovar la fragmentació d’una unitat amb PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Com comprovar l’espai en disc de les unitats amb 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
Com obrir un arxiu amb PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Com llegir un fitxer amb PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Com escriure la sortida a un fitxer amb 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 |
Com obtenir el nom complet del fitxer de script actual amb PowerShell?
$MyInvocation.MyCommand.Path
Com comprimir / zip arxius amb 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 |
Com descomprimir / unzip arxius amb 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) |
Com veure els arxius en un arxiu ZIP amb PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Com visualitzar la mida d’un arxiu en KB amb PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Com trobar arxius de més o menys d’1 GB amb 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} |
Com visualitzar el nom d’un arxiu sense l’extensió amb PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Com mostrar l’extensió d’un arxiu amb PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Com obtenir la versió d’arxiu d’un arxiu amb PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Com obtenir el hash d’un arxiu PowerShell?
(Get-FileHash $file).Hash
Com obtenir la suma de comprovació MD5 / SHA1 d’un arxiu amb PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Com mostrar els arxius ocults amb PowerShell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Com comprovar si un fitxer té una extensió amb PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Com configurar un arxiu com de només lectura amb PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Com canviar l’atribut LastWriteTime a la setmana passada per un arxiu amb PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Com crear un nou arxiu amb PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Com canviar el nom d’un arxiu amb PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Com incrementa / expandeix canviar el nom de diversos arxius amb PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Com esborrar un arxiu amb PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
Com visualitzar les 10 últimes línies d’un fitxer amb PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Com desbloquejar diversos arxius d’una carpeta amb PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Com eliminar les línies buides d’un arxiu amb PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Com comprovar si existeix un arxiu amb PowerShell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Com a descarregar el fitxer més nou / antic creat en una carpeta amb 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 |
Com eliminar les línies duplicades d’un arxiu amb 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 |
Com obtenir els arxius creats més / menys d’1 mes en una carpeta amb 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 |
Com obtenir els arxius creats de fa més / o menys 1 any en una carpeta amb 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 |
Com exportar el valor d’una variable en un arxiu amb PowerShell?
Set-Content -Path file.txt -Value $variable
Com comptar el nombre d’arxius (* .txt) en una carpeta amb 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 |
Com cercar una cadena dins de diversos arxius amb PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Com visualitzar la primera / última línia / d’un arxiu amb 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 |
Com mostrar un nombre de línia específica d’un arxiu amb 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 |
Com comptar el nombre de línies d’un fitxer amb PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Com comptar el nombre de caràcters i paraules d’un arxiu amb 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 |
Com descarregar un arxiu amb PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Com mostrar la ruta completa d’un arxiu amb PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Com copiar un fitxer a una carpeta amb PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Com copiar un arxiu a diverses carpetes en PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Com copiar diversos arxius a una carpeta en PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Com trobar servidors de catàleg global a l’Active Directory amb PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Com trobar llocs a l’Active Directory amb PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Com trobar el controlador de domini actual amb 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 |
Com trobar tots els controladors de domini en un domini amb PowerShell?
1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 Get-ADDomainController -Filter * | ForEach-Object -Process {$_.Name} # Solution 2 Get-ADGroupMember 'Domain Controllers' | ForEach-Object -Process {$_.Name} # Solution 3 Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))' | ForEach-Object -Process {$_.Name} # Solution 4 [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | ForEach-Object -Process {$_.DomainControllers} | ForEach-Object -Process {$_.Name} |
Com trobar els errors de replicació AD amb PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
Com trobar el periòde de rebuig per al bosc de l’Active Directory amb PowerShell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Com obtenir detalls del un bosc / domini a l’Active Directory amb PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Com obtenir la ruta del contenidor dels “Objectes eliminats” de l’Active Directory amb PowerShell?
(Get-ADDomain).DeletedObjectsContainer
Com habilitar la característica AD de la Paperera de reciclatge a l’Active Directory amb 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' |
Com restaurar un compte AD de la Paperera de reciclatge a l’Active Directory amb PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Com trobar les funcions FSMO amb 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 |
Com establir connexió a un controlador de domini específic amb PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'
Com aconseguir el servidor d’inici de sessió actual amb PowerShell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Com fer “gpupdate” en un equip amb PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Com crear un nou grup a l’Active Directory amb 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' |
Com eliminar un grup a l’Active Directory amb PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'
Com afegir un usuari a un grup a l’Active Directory amb PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Com eliminar un usuari d’un grup a l’Active Directory amb PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Com trobar grups buits (sense membres) a l’Active Directory amb PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Com comptar els grups buits (sense membres) a l’Active Directory amb PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Com arribar als membres d’un grup a l’Active Directory amb 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' | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.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' |
Com arribar als membres d’un grup amb participants recursius a l’Active Directory amb PowerShell?
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
Com utilitzar un comodí en el filtre de “Get-ADUser” a l’Active Directory amb 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 |
Com moure un usuari a un altre OU en Active Directory amb PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Com trobar tota la MemberOf (imbricada) per a un usuari amb PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Com obtenir el MemberOf (nom curt / truncat) per a un usuari amb PowerShell?
(Get-ADUser $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 |
Com canviar la descripció, Oficina i (Tele) número de telèfon per un compte d’usuari a l’Active Directory amb 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 |
Com desbloquejar un compte d’usuari a l’Active Directory amb PowerShell?
Unlock-ADAccount $samAccountName
Com activar / desactivar un compte d’usuari a l’Active Directory amb PowerShell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Com eliminar un compte d’usuari a l’Active Directory amb PowerShell?
Remove-ADUser $samAccountName
Com restablir una contrasenya per un compte d’usuari a l’Active Directory amb 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 |
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 |
Com trobar el propietari d’un arxiu a l’ Active Directory amb 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 |
Com trobar l’ OU (unitat organitzativa) per a un usuari a l’Active Directory amb PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Com trobar comptes d’usuaris amb discapacitat a l’Active Directory amb PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Com trobar comptes d’usuaris caducats a l’Active Directory amb PowerShell?
Search-ADAccount -AccountExpired
Com trobar comptes d’usuaris bloquejats a l’Active Directory amb PowerShell?
Search-ADAccount -LockedOut
Com trobar el SID d’un compte d’usuari a l’Active Directory amb PowerShell?
(Get-ADUser $user -Properties SID).SID.Value
Com convertir un nom d’usuari a SID a l’Active Directory amb PowerShell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Com convertir un SID de nom d’usuari en Active Directory amb PowerShell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
Com dividir el nom complet d’un compte d’usuari a l’ Active Directory amb 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" |
Com trobar la data de creació / modificació d’un compte d’usuari a l’ Active Directory amb 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 |
Com obtenir la ruta LDAP per a un usuari a l’Active Directory amb 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 |
Com canviar el CN ??(Nom Canònic) per a un usuari a l’Active Directory amb PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Com aconseguir la unitat organitzativa (OU) pare d’un usuari a l’Active Directory amb PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Com convertir l’atribut pwdLastSet per a un usuari a l’Active Directory amb PowerShell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Com provar el canal segur entre l’equip local i el domini amb PowerShell?
Test-ComputerSecureChannel
Com reparar el canal segur entre l’equip local i el domini amb PowerShell?
Test-ComputerSecureChannel -Repair
Com desactivar un compte d’equip en Active Directory amb PowerShell?
Disable-ADAccount $computer
Com trobar ordinadors amb un sistema operatiu específic a l’Active Directory amb 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)
Com crear una unitat organitzativa (OU) a l’Active Directory amb PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Com aconseguir els detalls de la la unitat organitzativa (OU) a l’Active Directory amb PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Com canviar la descripció d’una unitat organitzativa (OU) a l’Active Directory amb 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 |
Com llistar les unitats organitzatives (OU) buides amb 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 } |
Com aconseguir el gerent d’un grup amb PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Com extreure una adreça IP v4 (80.80.228.8) amb Regex amb 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
Com extreure una adreça MAC (C0-D9-62-39-61-2D) amb separador “-” amb Regex amb 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
Com extreure una adreça MAC (C0: D9: 62: 39: 61: 2D) amb separador “:” amb Regex amb 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
Com extreure una data (2015.02.10) amb Regex amb PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Com extreure un URL (www.powershell-guru.com) amb Regex amb PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Com extreure un correu electrònic (user@domain.com) amb Regex amb 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
Com extreure “guru” de l’exemple de cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Com extreure “guru.com” l’exemple de cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Com extreure “powershell-guru.com” l’exemple de cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Com extreure “123” en l’exemple de cadena amb Regex amb PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Com extreure “$” (signe de dòlar) a partir de l’exemple de cadena amb Regex amb PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Com reemplaçar un caràcter (* .com) amb un altre (* .fr) en una cadena amb Regex amb PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Com escapar d’una cadena amb Regex amb PowerShell?
[regex]::Escape('\\server\share')
Memory
Com forçar una col·lecció de memòria pel recol·lector d’escombraries amb PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Com obtenir la mida de la RAM d’un ordinador amb 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
Com obtenir la data actual amb PowerShell?
Get-Date
[Datetime]::Now
Com fer visible la data en diferents formats amb 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 |
Com convertir una data (data i hora) a la data (String) amb 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 |
Com convertir una data (String) fins a la data (data i hora) amb 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 |
Com calcular la diferència (nombre de dies, hores, minuts o segons) entre dues dates amb 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
Com comparar dues dates amb 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
Com ordenar una sèrie de dates com a data i hora amb PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Com iniciar i aturar un cronòmetre amb PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Com obtenir el dia actual de la setmana amb PowerShell?
(Get-Date).DayOfWeek #Sunday
Com obtenir la data d’ahir amb PowerShell?
(Get-Date).AddDays(-1)
Com obtenir el nombre de dies en un mes (al febrer de 2015) amb PowerShell?
[DateTime]::DaysInMonth(2015, 2)
Com saber si existeix un any de traspàs amb PowerShell?
[DateTime]::IsLeapYear(2015)
Com llistar zones horàries amb PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Com codificar (a format ASCII) i descodificar un URL amb 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 |
Quins són els equivalents dels comandaments de nadius amb 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 |
Com obtenir les adreces IP amb PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Com desactivar l’adreça v6 IP (IPv6) amb PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Com validar una adreça v4 IP (IPv4) amb PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}
Com trobar l’adreça IP externa amb 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 } |
Com trobar el nom d’amfitrió d’una adreça IP amb PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Com trobar l’adreça IP d’un nom de host amb PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Com trobar el nom complet d’un nom d’amfitrió amb PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
Com trobar la configuració de xarxa (IP, subxarxa, Gateway i DNS) amb PowerShell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Com trobar l’adreça MAC amb PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Com fer un so estrident a un ordinador amb 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) |
Com comprovar si un ordinador està connectat a Internet amb PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Com fer una cerca whois per a una pàgina web amb PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Com obtenir detalls d’IP pública (Geolocalització) amb PowerShell?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Com comprovar si un port està obert / tancat amb PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Com fer tracert amb PowerShell?
Test-NetConnection www.google.com -TraceRoute
Com corregir el perfil de connexió de xarxa a casa amb PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Com mostrar les connexions del port TCP amb PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Com escurçar un URL llarga en una diminuta URL amb PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Com obtenir la configuració de proxy amb PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Com comprovar la memòria cau de DNS a l’equip local amb PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Com esborrar la memòria cau DNS a l’equip local amb PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Com esborrar la memòria cau DNS en equips remots amb PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Com llegir el fitxer Hosts amb PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Com generar una contrasenya aleatòria amb PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Com canviar la contrasenya d’administrador local per al servidor remot amb PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Com trobar la data d’expiració de la contrasenya d’un compte en Active Directory amb 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 $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
Com llistar totes les impressores d’un servidor específic amb PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Com enumerar tots els ports d’un servidor específic amb PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Com canviar el comentari / ubicació per a una impressora amb 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() |
Com eliminar (cancel·lar tots els treballs) a una impressora amb PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Com imprimir una pàgina de prova per a una impressora amb PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Com aconseguir les cues d’impressió per a impressores amb 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
Com llistar seccions del Registre amb PowerShell?
Get-ChildItem -Path Registry::
Com obtenir els valors de registre i tipus de valor amb 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) } } } |
Com enumerar el registre de les subclaus de clau amb 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:\' |
Com enumerar el registre de les subclaus de clau en forma recursiva amb PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Com trobar subclaus amb un nom específic amb PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Com tornar només el nom del registre de les subclaus amb PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Com llistar els valors de registre amb PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Com llegir un valor de registre específic amb PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Com llegir un valor específic del registre en l’equip remot amb 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
Com crear una nova clau de registre amb PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'
Com crear un valor de registre amb PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Com modificar un valor de registre existent amb PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Com esborrar un valor de registre amb PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Com suprimir una clau de registre amb PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Com provar si hi ha una clau del Registre amb PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'
Com provar si hi ha un valor de registre amb PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Com eliminar caràcters d’espai en blanc des del principi d’una cadena amb PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Com eliminar caràcters d’espai en blanc del final d’una cadena amb PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Com eliminar caràcters d’espai en blanc (començar i acabar) d’una cadena amb PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()
Com convertir una cadena a majúscules amb PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()
Com convertir una cadena a minúscules amb PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Com seleccionar la subcadena “PowerShell” de la cadena “PowershellGuru” amb PowerShell?
$string.Substring(0,10)
Com seleccionar la subcadena “guru” de la cadena “PowershellGuru” amb PowerShell?
$string.Substring(10)
Com seleccionar el nombre “123” de “Powershell123Guru” amb PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Com obtenir l’índex de base zero de “Guru” del “PowershellGuru” cadena amb PowerShell?
$string.IndexOf('Guru') # 10
Com comprovar si una cadena és nula o buida amb PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Com comprovar si una cadena nul·la, buida, o es compon només de caràcters d’espai en blanc amb PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Com comprovar si una cadena conté una carta específica amb PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Com tornar la longitud d’una cadena amb PowerShell?
$string.Length
Com conectar dues cadenes amb PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Com fer coincidir un o diversos suports “[]” en una cadena amb PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Com fer coincidir un o diversos parèntesi “()” en una cadena amb PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Com fer coincidir una o diverses claus “{}” en una cadena amb PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Com fer coincidir un o diversos suports d’angle “& lt; & gt;” en una cadena amb PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Com fer coincidir les lletres minúscules (abc) en una cadena amb PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Com fer coincidir letras majúscules (ABC) en una cadena amb PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Com fer coincidir “[p” (p minúscula) en una cadena amb PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Com fer coincidir (P majúscula) “[P” en una cadena amb PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Com reemplaçar una línia amb una altra línia amb PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Com convertir una operació de divisió a una cadena (Percentatge) amb PowerShell?
(1/2).ToString('P')
Com ordenar cadenes que contenen nombres amb PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Com seleccionar l’última paraula d’una frase amb PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Com aconseguir la paraula més gran d’una oració amb PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Com comptar el nombre de vegades que una cadena és present dins d’una oració amb PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Com copiar cada caràcter en una cadena a una matriu de caràcters amb PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Com convertir la primera lletra en majúscules d’una cadena amb PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Com pad (esquerra o dreta) una cadena amb 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 |
Com codificar i descodificar una cadena de base 64 amb 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 |
Com convertir un nombre a binari (de i des de) amb 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) |
Com tornar només a la carpeta principal a un camí amb PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Com tornar només l’últim element d’un camí amb PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Com enumerar els mètodes de la classe System.Math amb PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
Com tornar el valor absolut amb PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Com tornar l’angle el si és el nombre especificat amb PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
Com tornar el sostre amb PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Com tornar el pis amb PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Com tornar la (base e) natural del logaritme d’un nombre específic amb PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
Com tornar el logaritme en base 10 d’un nombre específic amb PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
Com tornar un màxim de dos valors amb PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Com tornar un mínim de dos valors amb PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Com tornar un nombre elevat a la potència especificada amb PowerShell?
[Math]::Pow(2,4) #Returns 16
Com tornar un valor decimal en el valor integral propera amb PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Com tornar la part entera d’un nombre decimal especificat amb PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Com tornar l’arrel quadrada d’un nombre especificat amb PowerShell?
[Math]::Sqrt(16) #Returns 4
Com tornar la constant PI amb PowerShell?
[Math]::Pi #Returns 3,14159265358979
Com tornar la base logaritme natural (constant i) amb PowerShell?
[Math]::E #Returns 2,71828182845905
Com comprovar si un nombre és parell o senar amb PowerShell?
[bool]($number%2)
Hashtables
Com crear una taula buida hash amb PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Com crear una taula buida hash amb elements amb PowerShell?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
Com crear una taula hash ordenada per clau / nom (diccionari ordenat) amb elements amb PowerShell?
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
Com afegir elements (parell clau-valor) a una taula hash amb PowerShell?
$hashtable.Add('Key4', 'Value4')
Com obtenir un valor específic d’una taula hash amb PowerShell?
1 2 3 4 5 6 |
# Returns only Value $hashtable.Key1 $hashtable.Get_Item('Key1') # Returns Key and Value $hashtable.GetEnumerator() | Where-Object{$_.Name -eq 'Key1'} |
Com obtenir el valor mínim d’una taula hash amb 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 |
Com obtenir el màxim valor d’una taula hash amb 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 |
Com modificar els elements d’una taula hash amb PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Com eliminar elements en una taula hash amb PowerShell?
$hashtable.Remove('Key1')
Com esborrar una taula hash amb PowerShell?
$hashtable.Clear()
Com comprovar la presència d’una clau / valor específic en una taula hash amb PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Com ordenar per clau / valor en una taula hash amb PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Com crear una matriu buida amb PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()
Com crear una matriu amb elements amb PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Com afegir elements a una matriu amb PowerShell?
$array += 'D'
[void]$array.Add('D')
Com modificar un element d’una matriu amb PowerShell?
$array[0] = 'Z' # 1st item[0]
Com comprovar la mida d’una matriu amb PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Com recuperar un element / diversos / tots els elements d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Com eliminar elements buits en una matriu amb PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Com comprovar si hi ha un element d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Com trobar el número d’índex d’un element d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Com invertir l’ordre dels elements d’una matriu amb PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Com generar un element d’atzar d’una matriu amb PowerShell?
$array | Get-Random
Com ordenar una matriu en ordre ascendent / descendent amb PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Com comptar el nombre d’elements d’una matriu amb PowerShell?
$array.Count
Com afegir una matriu per una altra amb PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Com trobar duplicats d’una matriu amb PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C