Konsep: Die mees algemene vrae oor Powershell.
Jy kan hierdie lys op verskillende maniere gebruik:
- Om vinnig opdragte in ‘n script te Kopieer/plak
- Om vinnig die sintaksis van ‘n spesifieke opdrag te sien
- Om jou tegniese kennis te verbeter
- Om nuwe instruksies te ontdek
- Om vir ‘n werksonderhoud voor te berei
Opgedateer: |
2 Julie 2015
|
Skrywer | powershell-guru.com |
Bron | afrikaans.powershell-guru.com |
Kategorieë |
75
|
Vrae |
610
|
System
Hoe om my weergawe – “version” van PowerShell te bepaal?
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 } |
Hoe om PowerShell vir terugwerkende verenigbaarheid in ‘n ander weergawe te laat loop “run”?
powershell.exe -Version 2.0
Hoe kry ek die laagste PowerShell weergawe (3,0 en hoër) in ‘n teks “script” met PowerShell?
#Requires -Version 3.0
Hoe om administratiewe voorregte vir ‘n teks “script” aan te skaf met PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Hoe om die parameters van ‘n teks “script” met PowerShell te kontroleer?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Hoe kry ek inligting vir die huidige gebruiker met PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Hoe om ‘n profiel te skep, te wysig, en te herlaai met PowerShell?
1 2 3 4 5 6 7 8 9 |
# Create New-Item -Type file -Force $profile # Edit notepad.exe $profile # Reload (without restarting Powershell) & $profile .$profile |
Hoe om ‘n pouse van 5 sekondes/minute te maak in ‘n teks “script” met PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Hoe kry ek die laaste laai “boot” tyd met PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Hoe om die teks/tik versnellers “type accelerators” met PowerShell te kry ?
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 |
Hoe kry ek ‘n lys van die “startup” programme met PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Hoe om ‘n aplikasie met PowerShell te oninstalleer “uninstall”?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Hoe om ‘n skermskoot “screenshot” te neem van die hele, of net die aktiewe venster “window” met PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Hoe kry ek die boodskap getal vir MSMQ waglys met PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Hoe om die uitvoerbeleid met PowerShell op te stel?
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 |
Hoe om ‘n kortpad met PowerShell te skep?
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() |
Hoe om ‘n program met PowerShell te pen “pin” of ontpen “unpin” op die taakbalk ?
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
Hoe om Windows Explorer met PowerShell oop te maak?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Hoe om ‘n toestel sagtewareroetine “device drivers” met PowerShell te lys ?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Hoe om ‘n globale unieke identifiseerder “GUID” met PowerShell skep?
1 2 3 4 5 6 7 8 9 10 11 |
# Empty GUID $guid = [GUID]::Empty # New GUID (lower case by default) $guid = [GUID]::NewGuid() # New GUID (upper case) $guid = ([GUID]::NewGuid()).ToString().ToUpper() # New GUID with a specific value $guid = [GUID]('bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7') |
Hoe om die ligging vir die huidige gebruiker, van die tydelike gids “directory” met PowerShell te kry?
[System.IO.Path]::GetTempPath()
Hoe om ‘n baan “Path” en ‘n kind-baan “child path” in ‘n enkele baan “path” met PowerShell aan te sluit?
Join-Path -Path C:\ -ChildPath \windows
Hoe kry ek ‘n lys van al die cmdlets “Get- *” met PowerShell?
Get-Command -Verb Get
Hoe om met PowerShell ‘n lys van spesiale stelsel leêrgidse “system folders” te kry?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Hoe om ISO/VHD lêers met PowerShell te monteer?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Hoe om “.NET Framework” weergawes, geinstalleer met PowerShell, te kontroleer?
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 |
Hoe om te kyk of die .NET Framework weergawe 4.5 met PowerShell geïnstalleer is?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Hoe om ‘n transkripsie “transcript” met PowerShell te begin en te stop (om ‘n rekord van die Windows PowerShell sessie te skep)?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Hoe om die huidige gids met PowerShell te verander na ‘n spesifieke plek toe?
Set-Location -Path 'C:\scripts'
Hoe om die skerm met PowerShell te ontruim?
Clear-Host
cls # Alias
Hoe om die vertoon resolusie met PowerShell te verander?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Hoe om die vol-skerm venster “full screen” met PowerShell stel?
mode.com 300
Hoe kry ek die dimensies (breedte en hoogte) van ‘n foto met 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 } |
Hoe kry ek die Windows produk sleutel met 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
Hoe kry ek die huidige “% verwerker Tyd” – “prosessor time” (gemiddeld) in die laaste 5 sekondes (10 keer) met PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Hoe om samestellings “assemblies” met PowerShell te laai?
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') |
Hoe om huidige .NET samestellings “assemblies”, gelaai met PowerShell, te kontroleer?
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Hoe om resultate na die knipbord te kopieer met PowerShell?
1 |
Get-Process | clip.exe |
Hoe kry ek die inhoud van die knipbord met PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Hoe om met PowerShell die “hotfixes” te kry wat geïnstalleer is?
Get-HotFix -ComputerName $computer
Hoe om met PowerShell die “hotfixes” geïnstaleer te kry voor/na ‘n spesifieke datum?
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
Hoe om te kyk of ‘n “hotfix” met PowerShell geïnstalleer is?
Get-HotFix -Id KB2965142
Hoe om die “hotfixes” op ‘n afgeleë rekenaar met PowerShell te installeer?
Get-HotFix -ComputerName $computer
Pagefile
Hoe kry ek Pagina-lêer “Pagefile” inligting met PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Hoe kry ek die aanbevole grootte (MB) vir die pagina-lêer “Pagefile” met PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Hoe om ‘n pagina-lêer “Pagefile” met PowerShell (4096 MB) op die (D 🙂 dryf te skep?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Hoe om ‘n pagina-lêer “Pagefile” met PowerShell op die (C 🙂 dryf te verwyder?
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
Hoe om die fragmentering van ‘n dryf met PowerShell te kontroleer?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Hoe om die hardeskyf spasie van drywe met PowerShell te kontroleer?
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
Hoe om ‘n lêer met PowerShell oop te maak?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Hoe om ‘n lêer met PowerShell te lees?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Hoe om uitset “output” na ‘n lêer toe te skryf met PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
Hoe kry ek die hele naam van die huidige teks lêer “script file” met PowerShell?
$MyInvocation.MyCommand.Path
Hoe om lêers saam te pers “compress/zip files” met PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
Hoe om lêers met PowerShell te onkompakteer?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
Hoe om die lêers met PowerShell in ‘n saamgepersde argief – “zip archive” te sien?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Hoe om die grootte van ‘n lêer met PowerShell in KB te vertoon?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Hoe om lêers groter of kleiner as 1 GB met PowerShell te vind?
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} |
Hoe om die naam van ‘n lêer, sonder die uitbreiding, met PowerShell te vertoon ?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Hoe om die uitbreiding van ‘n lêer met PowerShell te vertoon?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Hoe kry ek die lêer weergawe van ‘n lêer met PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Hoe kry ek met PowerShell die huts – “hash” van ‘n lêer?
(Get-FileHash $file).Hash
Hoe kry ek met PowerShell die MD5/SHA1 kontrolesom – “checksum” van ‘n lêer?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Hoe om verborge lêers te vertoon met PowerShell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Hoe om te kyk of ‘n lêer ‘n uitbreiding het met PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Hoe om ‘n lêer met PowerShell as “Slegs Lees” te stel?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Hoe om die “LastWriteTime” kenmerk, met PowerShell vir ‘n lêer na verlede week toe te verander?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Hoe om ‘n nuwe lêer met PowerShell te skep?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Hoe om ‘n lêer met PowerShell te herbenoem “rename”?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Hoe om veelvuldige grootmaat/joernaal lêers met PowerShell te herbenoem “rename”?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Hoe om ‘n lêer met PowerShell te verwyder “delete”?
Remove-Item -Path 'C:\scripts\file.txt'
Hoe om die 10 nuutste lyne van ‘n lêer met PowerShell te vertoon?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Hoe om verskeie lêers “files” van ‘n lêergids “folders” met PowerShell te blok?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Hoe om leë lyne van ‘n lêer “file” met PowerShell te verwyder?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Hoe om met PowerShell te kyk of ‘n lêer bestaan ?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Hoe kry ek die nuutste/oudste geskepde lêer “file” in ‘n lêergids “folder” met 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 |
Hoe om duplikaat lyne van ‘n lêer “file” met PowerShell te verwyder?
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 |
Hoe kry ek lêers wat min of meer ‘n maand terug geskep is, in ‘n lêergids “folder” met 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 |
Hoe kry ek lêers “files” wat min of meer ‘n jaar terug geskep is in’n gids “folder” met 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 |
Hoe om die waarde van ‘n veranderlike na ‘n lêer met PowerShell uit te voer “export”?
Set-Content -Path file.txt -Value $variable
Hoe om die aantal (* .txt) lêers “files” in ‘n lêergids “folder” te tel met 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 |
Hoe om ‘n string binne veelvuldige lêers met PowerShell te soek?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Hoe om die eerste/laaste lyn van ‘n lêer met PowerShell te wys?
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 |
Hoe om ‘n spesifieke lyn nommer van ‘n lêer “file” met PowerShell te vertoon?
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 |
Hoe om die hoeveelheid lyne van ‘n lêer “file” met PowerShell te tel?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Hoe om die aantal karakters en woorde van ‘n lêer “file” met PowerShell te tel?
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 |
Hoe om ‘n lêer met PowerShell af te laai “download”?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Hoe om die volle baan van ‘n lêer “file” met PowerShell te wys?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Hoe om ‘n lêer “file” na ‘n lêergids “folder” toe te kopieer met PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Hoe om een lêer “file” na verskeie lêergidse “folders” toe te kopieer met PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Hoe om veelvuldige lêers “files” te kopieer na een lêergids “folder” toe met PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Hoe kry Globale katalogus bedieners “Global Catalogue Servers” in Active Directory met PowerShell??
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Hoe kry ek ruimtes “sites” met PowerShell in Active Directoryl?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Hoe kry ek die huidige domein kontroleerder “Domain Controller” met PowerShell?
(Get-ADDomainController).HostName
Hoe kry ek al die domein kontroleurs “domain controllers” met PowerShell in ‘n afdeling?
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} |
Hoe kry ek die AD replikasie mislukkings “replication failures” met PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Hoe vind ek die besonderhede van die bos/domein in Active Directory met PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Hoe kry ek die baan van die uitgewisde voorwerpe houer “deleted objects” in die Active Directory met PowerShell?
(Get-ADDomain).DeletedObjectsContainer
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' |
Hoe om ‘n AD rekening van die herwinnings blik “Recycle Bin” met PowerShell te herstel in’n aktiewe gids Active Directory?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Hoe om die “FSMO” rolle met PowerShell te vind?
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 |
Hoe om by ‘n spesifieke domein kontroleerder “domain controller” met PowerShell aan te sluit ?
Get-ADUser -Identity $user -Server 'serverDC01'
Hoe kry jy die huidige aanmeld bediener “current logon server” met PowerShell ?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Hoe voer jy met PowerShell “GPUpdate” uit op ‘n rekenaar ?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Hoe om ‘n nuwe groep in Active Directory met PowerShell te skep?
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' |
Hoe om ‘n groep in Active Directory met PowerShell te verwyder?
Remove-ADGroup -Identity 'PowershellGuru'
Hoe om ‘n gebruiker met PowerShell in ‘n groep te in te deel wat in Active Directory is?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Hoe om ‘n gebruiker met PowerShell uit ‘n groep te haal wat in Active Directory is?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Hoe om leë groepe (sonder enige lede) in Active Directory met PowerShell te vind?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Hoe om leë groepe (sonder enige lede) in Active Directory te tel met PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Hoe om die lede van ‘n groep in Active Directory met PowerShell in te kry?
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' |
Hoe om met PowerShell die lede van ‘n groep te kry met rekursiewe lede in Active Directory?
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
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 |
Hoe om ‘n gebruiker met PowerShell na ‘n ander “OU” te beweeg in Active Directory ?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Hoe om al die lede wat ge-nes (Nested) is vir ‘n gebruiker, met PowerShell te vind?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Hoe om met PowerShell die lede (afgeknot/afgekap) (truncated/short name) te kry vir ‘n gebruiker?
(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 |
Hoe om die beskrywing, kantoor- en telefoonnommer vir ‘n rekening in Active Directory met PowerShell te verander?
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 |
Hoe om ‘n rekening in Active Directory met PowerShell oop te sluit “unlock”?
Unlock-ADAccount $samAccountName
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Hoe om ‘n rekening in Active Directory te verwyder met PowerShell?
Remove-ADUser $samAccountName
Hoe om ‘n wagwoord vir een rekening in Active Directory te herstel met 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 |
Hoe om die eienaar van ‘n lêer in Active Directory met PowerShell te vind?
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 |
Hoe om die “OU” (Organizational Unit) vir ‘n gebruiker “user” in Active Directory met PowerShell te vind?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Hoe om verstreke gebruiker rekeninge “user accounts” in Active Directory met PowerShell te vind?
Search-ADAccount -AccountExpired
Hoe om gevriesde/geslote gebruikers rekeninge – “closed user accounts” met PowerShell in Active Directory te vind?
Search-ADAccount -LockedOut
Hoe om die SID van ‘n rekening “user account” in Active Directory met PowerShell te vind?
(Get-ADUser $user -Properties SID).SID.Value
Hoe om ‘n gebruikersnaam “username” in Active Directory te omskep na SID met PowerShell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Hoe om ‘n SID met PowerShell in ‘n gebruikersnaam te omskep, in Active Directory?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
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" |
Hoe om die datum van die skepping/wysiging “creation/modification” van ‘n rekening “user account” in Active Directory met PowerShell te vind?
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 |
Hoe kry jy die LDAP roete vir ‘n gebruiker in Active Directory met 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 |
Hoe om die CN (kanoniese Naam/doopnaam) vir ‘n gebruiker in Active Directory met PowerShell te verander?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test 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 |
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Hoe om die beveiligde kanaal “secure channel” tussen die plaaslike rekenaar en die domein met PowerShell te toets?
Test-ComputerSecureChannel
Hoe herstel jy die beveiligde kanaal tussen die plaaslike rekenaar en die domein met PowerShell?
Test-ComputerSecureChannel -Repair
Hoe om ‘n rekenaar rekening in Active Directory met PowerShell te versper/af te skakel “disable”?
Disable-ADAccount $computer
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)
Hoe skep jy ‘n organisatoriese eenheid (OU) “organisational unit” in Active Directory met PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Hoe vind jy organisatoriese eenheid (OU)”organisational unit” besonderhede in Active Directory met PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Hoe om die beskrywing van ‘n organisatoriese eenheid (OU) “Organizational Unit” in Active Directory te verander met 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 |
Hoe om leë Organisasie-eenhede “organisational units”(OU) met PowerShell te lys?
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 } |
Hoe om die bestuurder van ‘n groep met PowerShell te kry?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Hoe om ‘n IP-adres v4 (80.80.228.8) met Regex met PowerShell te onttrek?
$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
Hoe om ‘n MAC-adres (C0-D9-62-39-61-2D) met die skeikarakter “separator” “-” te onttrek met Regex met 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
Hoe om ‘n MAC-adres (C0:D9:62:39:61:2D) met die skeikarakter “separator” “:” te onttrek met Regex met 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
Hoe om ‘n datum (2015/10/02) met Regex met PowerShell te onttrek?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Hoe om ‘n URL (www.powershell-guru.com) met Regex met PowerShell te onttrek?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Hoe om ‘n e-pos (user@domain.com) met Regex met PowerShell te onttrek?
$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
Hoe om “guru” uit die string voorbeeld te ontrek/uit te haal, met Regex met PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Hoe om “guru.com” uit die string voorbeeld te ontrek/uit te haal, met Regex met PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Hoe om “powershell-guru.com” uit die string voorbeeld te ontrek/uit te haal, met Regex met PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Hoe om “123” uit die string voorbeeld met Regex met PowerShell te onttrek?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Hoe om “$” (dollar teken) van die string voorbeeld met Regex met PowerShell te onttrek?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Hoe om ‘n karakter (* com) met ‘n ander (* Fr) te vervang in ‘n string met Regex met PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Hoe om ‘n string te ontsnap “escape” met Regex met PowerShell?
[regex]::Escape('\\server\share')
Memory
Hoe om die versamelde geheue “memory” met PowerShell te dwing/forseer “force” na die vullis versamelaar toe?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Hoe om die RAM grootte van ‘n rekenaar met PowerShell te kry?
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
Hoe om die huidige datum met PowerShell te kry?
Get-Date
[Datetime]::Now
Hoe om die datum in verskillende formate met PowerShell te vertoon?
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 |
### DATE ### Get-Date -Format d : 15/04/2015 Get-Date -Format D : 15 April 2015 Get-Date -Format f : 15 April 2015 14:57 Get-Date -Format F : 15 April 2015 14:57:34 Get-Date -Format g : 15/04/2015 14:57 Get-Date -Format G : 15/04/2015 14:57:34 Get-Date -Format yyyyMMdd : 20150415 Get-Date -UFormat '%d%m%Y' : 15042015 Get-Date -UFormat '%m%d%Y' : 04152015 Get-Date -UFormat '%Y%m%d' : 20150415 Get-Date -UFormat '%d%m%Y' : 15-04-2015 Get-Date -UFormat '%m%d%Y' : 04-15-2015 Get-Date -UFormat '%Y%m%d' : 2015-04-15 ### HOUR ### Get-Date -Format t : 15:31 Get-Date -Format T : 15:31:44 Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 57 (Minute) Get-Date -Format ss : 34 (Seconds) Get-Date -DisplayHint Time : 15:31:44 ### DAY ### Get-Date -Format dddd : Wednesday Get-Date -Format ddd : Wed Get-Date -Format dd : 15 ### MONTH ### Get-Date -Format MMMM : April Get-Date -Format MMM : Apr Get-Date -Format MM : 04 ### YEAR ### Get-Date -Format yyyy : 2015 |
Hoe om ‘n datum tyd (Date Time) om te skakel na ‘n datum string (String) toe met PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
Hoe om ‘n datum string (String) om te skakel na ‘n datum tyd (Date Time) toe met PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
Hoe om die verskil (aantal dae, ure, minute of sekondes) te bereken tussen twee datums met 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
Hoe om twee datums te vergelyk met 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
Hoe om ‘n verskeidenheid van datums as datum tyd “DateTime” met PowerShell uit te sorteer?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Hoe om ‘n stophorlosie te begin en te stop met PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Hoe om die huidige dag van die week met PowerShell te kry?
(Get-Date).DayOfWeek #Sunday
Hoe om gister se datum met PowerShell te kry?
(Get-Date).AddDays(-1)
Hoe om die aantal dae van ‘n maand (in Februarie 2015) met PowerShell te kry?
[DateTime]::DaysInMonth(2015, 2)
Hoe om ‘n skrikkeljaar te vind met PowerShell?
[DateTime]::IsLeapYear(2015)
Hoe om tydsones te lys met PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Hoe om ‘n URL met PowerShell te enkodeer (om ASCII-formaat) en ontsyfer?
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 |
Wat is die ekwivalente van inheemse netwerk instruksies met 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 |
Hoe om IP adresse met PowerShell te kry?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Hoe om IP-adres v6 (IPv6) te sper “disable” met PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Hoe om ‘n IP-adres v4 (IPv4) met PowerShell geldig te maak “validate”?
if([ipaddress]'10.0.0.1'){'validated'}
Hoe om die eksterne IP-adres met PowerShell te vind?
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 } |
Hoe om die gasheer naam “Hostname” van ‘n IP-adres met PowerShell te vind?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Hoe om die IP-adres van ‘n gasheer naam “Hostname” met PowerShell te vind?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Hoe om die FQDN van ‘n gasheernaam “Hostname” te vind met PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Hoe om die MAC-adres met PowerShell te vind?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Hoe om ‘n rekenaar met PowerShell te ping?
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) |
Hoe om te kyk of ‘n rekenaar verbind is aan die internet met PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Hoe om ‘n wie is? “whois” soektog te begin vir ‘n webwerf met PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Hoe om die besonderhede van ‘n openbare IP (Geolocation) met PowerShell te kry?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Hoe om te kyk of ‘n poort oop/toe is met PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Hoe om ‘n “tracert” uit te voer met PowerShell?
Test-NetConnection www.google.com -TraceRoute
Hoe om ‘n tuis netwerk verbinding profiel met PowerShell reg te maak?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Hoe om die TCP-poort verbindings met PowerShell te wys?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Hoe om ‘n lang URL verkort na ‘n klein URL met PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Hoe om proxy settings te kry met PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Hoe om die DNS-kas “cache” na te gaan op ‘n plaaslike rekenaar met PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Hoe om ‘n DNS-kas “cache” op ‘n plaaslike rekenaar met PowerShell skoon te maak?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Hoe om ‘n DNS-kas “cache” op afgeleë rekenaars met PowerShell skoon te maak?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Hoe om die gasheer lêer “hostfile” te lees met PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Hoe om ‘n ewekansige wagwoord “random password” met PowerShell te genereer?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Hoe om die plaaslike wagwoord “password” vir ‘n administrateur op ‘n afgeleë “remote” bediener “server” met PowerShell te verander?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
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
Hoe om ‘n lys van al die drukkers vir ‘n spesifieke bediener “server” met PowerShell te kry?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Hoe om ‘n lys van al die poorte vir ‘n spesifieke bediener “server” met PowerShell te kry?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Hoe om die kommentaar/ligging “location” van ‘n drukker met PowerShell te verander?
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() |
Hoe om (alle poste te kanselleer)’n drukker skoon te maak “purge” met PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Hoe om ‘n toets bladsy te druk vir ‘n drukker met PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Hoe om druk toue te kry vir drukkers met 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
Hoe om ‘n lys van register korwe “registry hives” met PowerShell te ry?
Get-ChildItem -Path Registry::
Hoe om register waardes “registry values” en waarde tipes “value types” te kry met 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) } } } |
Hoe om ‘n lys te kry van die register sleutel subsleutels met 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:\' |
Hoe om ‘n lyste kry van die register sleutel subsleutels “registry key subkeys” op ‘n rekursiewe “recursive” manier met PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Hoe om subsleutels met ‘n spesifieke naam met PowerShell te vind?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Hoe om slegs die naam van die register subsleutels met PowerShell terug te eis?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Hoe om waardes in die register met PowerShell te lys?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Hoe om ‘n spesifieke register waarde met PowerShell te lees?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Hoe om ‘n spesifieke register “registry” waarde op ‘n afgeleë rekenaar met PowerShell te lees?
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
Hoe om ‘n nuwe register sleutel “registry key” met PowerShell skep?
New-Item -Path 'HKCU:\Software\MyApplication'
Hoe om ‘n register waarde met PowerShell te skep?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Hoe om ‘n bestaande register “registry” waarde met PowerShell te verander?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Hoe om ‘n register “registry” waarde met PowerShell te verwyder “delete”?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Hoe om ‘n register “registry” sleutel met PowerShell te verwyder “delete”?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Hoe om met PowerShell te toets of ‘n register “registry” sleutel bestaan?
Test-Path -Path 'HKCU:\Software\MyApplication'
Hoe om met PowerShell te toets of ‘n register “registry” waarde bestaan?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Hoe om wit-ruimte karakters met PowerShell, van die begin van ‘n string af, te verwyder?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Hoe om wit-ruimte karakters met PowerShell van die einde van ‘n string af, te verwyder?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Hoe om wit-ruimte karakters (begin en einde) met PowerShell van ‘n string af te verwyder?
$string = ' PowershellGuru '
$string = $string.Trim()
Hoe om ‘n string met PowerShell om te skakel na hoofletters toe?
$string = 'powershellguru'
$string = $string.ToUpper()
Hoe om ‘n string met PowerShell na kleinletters toe te omskep?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Hoe om die substring “PowerShell” van die string “PowerShellGuru” met PowerShell te kies?
$string.Substring(0,10)
Hoe om met PowerShell die substring “Guru” van die string “PowerShellGuru” te kies?
$string.Substring(10)
Hoe om die nommer “123” van “PowerShell123Guru” met PowerShell te kies?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Hoe om die nul-gebaseerde indeks van “Guru” van die string “PowerShellGuru” met PowerShell te kry?
$string.IndexOf('Guru') # 10
Hoe om te kyk of ‘n string null of leeg is met PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Hoe om te kyk of ‘n string null, leeg, of slegs uit wit-ruimte karakters uit bestaan met PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Hoe om met PowerShell te kyk of ‘n string ‘n spesifieke letter bevat?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Hoe om met PowerShell terug te keer na die lengte van ‘n string toe?
$string.Length
Hoe om twee stringe met PowerShell te koppel/aaneen te skakel?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Hoe om met PowerShell in ‘n string te pas/paar vir een of meer hakies “[]”?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Hoe om met PowerShell in ‘n string te pas/paar vir een of meer hakies “()”?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Hoe om met PowerShell in ‘n string te pas/paar vir een of meer krul hakies “{}”?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Hoe om met PowerShell in ‘n string te pas/paar vir een of meer hoek hakies “<>”?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Hoe om enige klein letters (abc) met PowerShell in ‘n string te pas/paar?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Hoe om hoofletters (ABC) met PowerShell in ‘n string te pas/paar?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Hoe om “[p” (p kleinletters) in ‘n string met PowerShell te pas/paar ?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Hoe “[P” (P hoofletters) in ‘n string met PowerShell te pas/paar?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Hoe om een lyn met ‘n ander lyn te vervang met PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Hoe om met PowerShell ‘n afdeling werking “division operation” om te skakel na ‘n string (persentasie) toe?
(1/2).ToString('P')
Hoe om stringe wat getalle bevat met PowerShell uit te sorteer?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Hoe om die laaste woord van ‘n sin met PowerShell te kies?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Hoe om die grootste woord van ‘n sin met PowerShell te kry?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Hoe om met PowerShell te tel hoeveel keer ‘n string voorkom binne in ‘n sin?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Hoe om met PowerShell elke karakter in ‘n string te kopieer na ‘n karakter”array” “character array”?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Hoe om die eerste letter van ‘n string met PowerShell na hoofletters te verander?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Hoe om (links of regs) ‘n string op te vul “pad” met 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 |
Hoe om n string met PowerShell te enkodeer en dekodeer na Base64 toe?
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 |
Hoe om ‘n nommer met PowerShell te omskep (na en van) na binêre/diadies “binary” toe?
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) |
Hoe om net die laaste ouer gids met PowerShell terug te bring in ‘n baan “path” in ?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Hoe om net die laaste item met PowerShell terug in ‘n baan in “path” te bring?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Hoe om met PowerShell die metodes van die System.Math klas te lys ?
[System.Math] | Get-Member -Static -MemberType Method
Hoe om die antwoord vir absolute waarde “absolute value” met PowerShell te kry?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Hoe om met PowerShell die antwoord te kry van die hoek waarvan sine die gespesifiseerde nommer is?
[Math]::ASin(1) #Returns 1,5707963267949
Hoe om die plafon waarde met PowerShell te kry?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Hoe om die vloer waarde met PowerShell te kry?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Hoe om die natuurlike (basis e) logaritme van ‘n gespesifiseerde nommer/getal met PowerShell te kry?
[Math]::Log(4) #Returns 1,38629436111989
Hoe om die basis 10 logaritme van ‘n gespesifiseerde nommer/getal met PowerShell te kry?
[Math]::Log10(4) #Returns 0,602059991327962
Hoe om die maksimum van twee waardes met PowerShell te kry?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Hoe om die minimum van twee waardes met PowerShell te kry?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Hoe om ‘n nommer/getal verhewe tot ‘n bepaalde bevoegdheid met PowerShell te kry?
[Math]::Pow(2,4) #Returns 16
Hoe om ‘n desimale waarde aan die naaste integrale waarde met PowerShell te kry?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Hoe om die integrale deel van ‘n bepaalde desimale getal met PowerShell te kry?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Hoe om die vierkantswortel van ‘n gespesifiseerde nommer/getal met PowerShell te kry?
[Math]::Sqrt(16) #Returns 4
Hoe om die PI konstante met PowerShell te kry?
[Math]::Pi #Returns 3,14159265358979
Hoe om die natuurlike logaritmiese basis (konstante e) met PowerShell te kry?
[Math]::E #Returns 2,71828182845905
Hoe om te kyk of ‘n getal ewe of onewe is met PowerShell?
[bool]($number%2)
Hashtables
Hoe om ‘n leë huts tabel “hashtable” met PowerShell te skep?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Hoe om ‘n huts tabel “hashtable” met items in met PowerShell te skep?
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 |
Hoe om items by ‘n hutstabel te voeg (sleutel-waarde paar) met PowerShell?
$hashtable.Add('Key3', 'Value3')
Hoe om ‘n spesifieke waarde van ‘n hutstabel “hashtable” met PowerShell te kry?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Hoe om die minimum waarde van ‘n hutstabel “hashtable” met PowerShell te kry?
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 |
Hoe om die maksimum waarde van ‘n hutstabel “hashtable” met PowerShell te kry?
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 |
Hoe om items in ‘n hutstabel “hashtable” met PowerShell te verander?
$hashtable.Set_Item('Key1', 'Value1Updated')
Hoe om items in ‘n hutstabel “hashtable” met PowerShell te verwyder ?
$hashtable.Remove('Key1')
Hoe om ‘n hutstabel “hashtable” met PowerShell skoon te maak?
$hashtable.Clear()
Hoe om te soek vir die teenwoordigheid van ‘n spesifieke sleutel/waarde in so ‘n hutstabel “hashtable” met PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Hoe om volgens sleutel/waarde deur ‘n hutstabel “hashtable” met PowerShell te sorteer?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Hoe om ‘n leë array met PowerShell te skep?
$array = @()
$array = [System.Collections.ArrayList]@()
Hoe om ‘n array met items in met PowerShell skep?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Hoe om items by ‘n array te voeg met PowerShell?
$array += 'D'
[void]$array.Add('D')
Hoe om ‘n item in ‘n array te verander met PowerShell?
$array[0] = 'Z' # 1st item[0]
Hoe om die grootte van ‘n array met PowerShell te toets?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Hoe om een/verskeie/alle items met PowerShell in ‘n array te kry?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Hoe om leë items met PowerShell uit ‘n array uit te verwyder ?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Hoe om met PowerShellte kyk of ‘n item binne in ‘n array bestaan?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Hoe om met PowerShell die indeks nommer van ‘n item in ‘n array te vind?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Hoe om met PowerShell, die orde van die items in ‘n array om te keer?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Hoe om ‘n ewekansige item uit ‘n array met PowerShell te genereer?
$array | Get-Random
Hoe om ‘n array in ‘n stygende/dalende manier met PowerShell te organiseer?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Hoe om die aantal items in ‘n array te tel met PowerShell?
$array.Count
Hoe om een array by ‘n ander te voeg met PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Hoe om duplikaat arrays met PowerShell te vind?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
Hoe om duplikaat arrays met PowerShell te verwyder?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
Hoe om ‘n array met PowerShell te skep met items wat begin met ‘n voorvoegsel (“user01”, “user02”, … “user10”)?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Hoe om die “ACL” van ‘n “AD” gebruiker met PowerShell te lys?
(Get-Acl -Path "AD:\$dn").Access
Hoe om die “ACL” van ‘n gids “folder” met PowerShell te lys?
(Get-Acl -Path C:\scripts).Access
1 |
((Get-Acl -Path "AD:\$dn").Access | Select-Object -Property IdentityReference | Where-Object -FilterScript {$_.IdentityReference -match 'Admin'} | Get-Unique | ForEach-Object -Process {$_.IdentityReference}).Value |
Variables
Wat is die mees algemene data tipes wat met PowerShell gebruik word?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[bool]$variable = $true [byte]$variable = ('0x10') [char]$variable = 0x260E [datetime]$variable = Get-Date [decimal]$variable = 1.89 [double]$variable = 1.89 [float]$variable = 1.89 [guid]$variable = 'b19b2a2e-ce1b-4b62-844f-ac8829ffbe8f' [int16]$variable = -32767 [int32]$variable = -2147483647 [int64]$variable = -9223372036854775807 [string]$variable = 'test' [uint16]$variable = 32767 [uint32]$variable = 2147483647 [uint64]$variable = 9223372036854775807 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[int] (integer) # int16 : MIN:-32768 MAX:32767 'MIN:{1:D} MAX:{0:D}' -f [int16]::MaxValue, [int16]::MinValue # int32 : MIN:-2147483648 MAX:2147483647 'MIN:{1:D} MAX:{0:D}' -f [int32]::MaxValue, [int32]::MinValue # int64 : MIN:-9223372036854775808 MAX:9223372036854775807 'MIN:{1:D} MAX:{0:D}' -f [int64]::MaxValue, [int64]::MinValue [uint] (u = unsigned, only positive numbers) # int16 : MAX:65535 'MAX:{0:D}' -f [uint16]::MaxValue # int32 : MAX:4294967295 'MAX:{0:D}' -f [uint32]::MaxValue # int64 : MAX:18446744073709551615 'MAX:{0:D}' -f [uint64]::MaxValue |
Hoe om die data tipe met PowerShell te toets?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
Hoe om ‘n Hier-String veranderlike “here-string variable” met PowerShell te skep?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Without variable $hereString = @" My first name is Test My last name is Powershell "@ # With variable $firstName = 'Test' $lastName = 'Powershell' $hereString = @" My first name is ${firstName} My last name is ${lastName} "@ |
Hoe om ‘n veranderlike “variable” met PowerShell te skep?
$powershellGuru = 'Hello'
Hoe om ‘n konstante veranderlike “contant variable” met PowerShell te skep?
Set-Variable -Name powershellGuru -Value 2015 -Option Constant
Hoe om ‘n globale veranderlike “global variable” met PowerShell te skep?
$Global:powershellGuru = 'Hello'
Hoe om ‘n veranderlike “variable” met PowerShell te lees?
$powershellGuru = 'Hello' # Create
$powershellGuru # Read
Get-Variable -Name powershellGuru -ValueOnly # Read
Hoe om die tipe veranderlike met PowerShell te verifieer?
$powershellGuru.GetType()
Hoe om die veranderlikes “variables” in die globale omvang “global scope” met PowerShell te vind?
Get-Variable -Scope Global
Hoe om spesifieke veranderlikes “specifick variables” deur hulle name te kry met PowerShell?
Get-Variable -Include *Preference -Exclude W*
Hoe om ‘n spesifieke data tipe aan ‘n veranderlike “variable” met PowerShell toe te wys?
[int64]$variable = 100
[string]$variable = 'PowershellGuru'
Hoe om meervoudige veranderlikes “multiple variables” te inisialiseer tot dieselfde waarde as PowerShell?
$a = $b = $c = $d = $e = 0
Wat is die alias vir die veranderlike “$_” met PowerShell?
Get-Process | Where-Object -FilterScript {$_.Handles -gt 1000} # Using $_
Get-Process | Where-Object -FilterScript {$PSItem.Handles -gt 1000} # Using $PSItem (since version 3)
Hoe om veranderlikes te verwyder met ‘n naam wat begin met “count” met PowerShell?
Remove-Variable -Name count*
Hoe om die plaaslike omgewings veranderlikes “local environment variables” met PowerShell te kry?
Get-ChildItem -Path Env:
Hoe om die Baan Omgewings Veranderlike “Path Environmental Variable” lyn vir lyn met PowerShell te kry?
($env:Path) -replace(';', "`n")
[Environment]::GetEnvironmentVariable('Path') -replace(';', "`n")
Hoe om ‘n nuwe baan (ex C.: \ SysinternalsSuite) by die Baan Omgewings Veranderlike “Path Environmental Variable” te voeg met PowerShell?
$env:Path += ';C:\SysinternalsSuite'
$env:Path = $env:Path + ';C:\SysinternalsSuite'
Hoe om veranderlikes aaneen te skakel met PowerShell?
$a = 'Powershell'
$b = '- Guru'
$c = $a + $b
Hoe om die “ErrorVariable” met PowerShell te gebruik?
Get-ChildItem -Path 'C:\PerfLogs' -ErrorAction SilentlyContinue -ErrorVariable AccessDenied
$AccessDenied | ForEach-Object -Process {$_.Exception}
$AccessDenied | ForEach-Object -Process {$_.TargetObject}
1 2 3 4 5 6 7 |
#Enable Set-PSDebug -Strict $a #The variable '$a' cannot be retrieved because it has not been set. # Disable Set-PSDebug -Off $a #No error displayed |
Static .NET Methods
Hoe om statiese lede met PowerShell te kry?
[DateTime] | Get-Member -Static
Sounds
Hoe om die “roep” klank speel met PowerShell?
[System.Console]::Beep()
Hoe om die “asterisk” klank speel met PowerShell?
[System.Media.SystemSounds]::Asterisk.Play()
Hoe om die “uitroep” klank speel met PowerShell?
[System.Media.SystemSounds]::Exclamation.Play()
Hoe om beskikbare klanke te kry met PowerShell?
[System.Media.SystemSounds] | Get-Member -Static
Hoe om “WAV” klanke met PowerShell te speel?
$soundPlayer = New-Object -TypeName System.Media.SoundPlayer -ArgumentList "$env:windir\Media\Ringout.wav"
$soundPlayer.Play()
of
$soundPlayer.PlayLooping()
$soundPlayer.Stop()
Hoe om spraak geskrewe teks met PowerShell te aktiveer?
Add-Type -AssemblyName System.Speech
$speech = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$speech.Speak('Hello PowershellGuru')
XML
Hoe om ‘n XML-lêer met PowerShell te lees?
[xml]$sitemap = Get-Content -Path .\sitemap.xml
$sitemap.urlset.url
Hoe om data uit te voer as ‘n XML-lêer met PowerShell?
Get-Process | Export-Clixml -Path C:\scripts\processes.xml
Hoe om data van ‘n CLIXML lêer met PowerShell in te voer?
$importProcesses = Import-Clixml -Path C:\scripts\processes.xml
GUI
Hoe om ‘n basiese GUI (Windows Form) met PowerShell te skep?
1 2 3 4 5 6 7 8 9 10 11 12 |
Add-Type -AssemblyName System.Windows.Forms $form = New-Object -TypeName system.Windows.Forms.Form $label = New-Object -TypeName System.Windows.Forms.Label $label.Text = 'PowershellGuru' $label.AutoSize = $true $label.Location = New-Object -TypeName Drawing.Point -ArgumentList 5, 10 $button = New-Object -TypeName Windows.Forms.Button $button.Text = 'OK' $button.Location = New-Object -TypeName Drawing.Point -ArgumentList 5, 30 $form.Controls.Add($label) $form.Controls.Add($button) $form.ShowDialog() |
Characters
Hoe om met PowerShell die ASCII waarde om te skakel na ‘n karakter toe?
[char]64
Hoe om ‘n karakter om te skakel na die ASCII waarde toe met PowerShell?
[int][char]'@'
Hoe om die Engelse alfabet met PowerShell te genereer?
[char[]](97..122)
Compare
Hoe om twee “arrays” te vergelyk met PowerShell?
1 2 3 4 5 |
$a = @(1, 2, 3) $b = @(2, 3) Compare-Object -ReferenceObject $a -DifferenceObject $b -IncludeEqual | Where-Object -FilterScript {$_.SideIndicator -eq '<='} # Returns 1 Compare-Object -ReferenceObject $a -DifferenceObject $b -IncludeEqual | Where-Object -FilterScript {$_.SideIndicator -ne '=='} # Returns 1 Compare-Object -ReferenceObject $a -DifferenceObject $b -IncludeEqual | Where-Object -FilterScript {$_.SideIndicator -eq '=='} # Returns 2 and 3 |
Hoe om twee prosesse met PowerShell te vergelyk?
1 2 3 |
$process1 = Get-Process -Id 8248 $process2 = Get-Process -Id 376 Compare-Object -ReferenceObject $process1 -DifferenceObject $process2 -Property Handles, NPM, PM, WS, VM, CPU |
Microsoft Exchange
Hoe om die lys van mobiele toestelle wat gesinchroniseer is met gebruikers se e-posbusse met PowerShell te kry?
Get-ActiveSyncDeviceStatistics
Hoe om “Full Access” volle toegang toestemming te gee vir ‘n e-posbus, vir ‘n gebruiker met PowerShell?
Add-MailboxPermission -Identity $dn -User 'DOMAIN\powershellguru' -AccessRights 'FullAccess'
Hoe om “Full Access” volle toegang toestemming te verwyder in ‘n e-posbus vir ‘n gebruiker met PowerShell?
Remove-MailboxPermission -Identity $dn -User 'DOMAIN\powershellguru' -AccessRights 'FullAccess' -InheritanceType 'All'
Hoe om “Send As” toestemming te gee vir ‘n e-posbus vir ‘n gebruiker met PowerShell?
Add-ADPermission -Identity $dn -User 'DOMAIN\powershellguru' -ExtendedRights 'Send-As'
Hoe om “Send As” toestemming terug te trek vir ‘n e-posbus vir ‘n gebruiker met PowerShell?
1 |
Remove-ADPermission -Identity $dn -User 'DOMAIN\powershellguru' -ExtendedRights 'Send-As' -InheritanceType 'All' -ChildObjectTypes $null -InheritedObjectTypes $null -Properties $null |
Hoe om die “inbox” reëls van ‘n e-posbus met PowerShell te vind?
Get-InboxRule -Mailbox 'Powershell.Guru'
Hoe om die SMTP-adres vir gebruikers wat OWA (Outlook Web Access) het aan te skakel met PowerShell?
Get-CASMailbox -Filter{OWAEnabled -eq $true} | Select-Object -Property Name, PrimarySMTPAddress
Exchange 2007
1 2 |
ServerManagerCmd -i RSAT-ADDS ServerManagerCmd -i PowerShell Web-Server Web-ISAPI-Ext Web-Metabase Web-Lgcy-Mgmt-Console Web-Basic-Auth Web-Digest-Auth Web-Windows-Auth Web-Dyn-Compression RPC-over-HTTP-proxy |
Exchange 2010
1 2 3 |
Import-Module -Name ServerManager Add-WindowsFeature NET-Framework, RSAT-ADDS, Web-Server, Web-Basic-Auth, Web-Windows-Auth, Web-Metabase, Web-Net-Ext, Web-Lgcy-Mgmt-Console, WAS-Process-Model, RSAT-Web-Server, Web-ISAPI-Ext, Web-Digest-Auth, Web-Dyn-Compression, NET-HTTP-Activation, RPC- Over-HTTP-Proxy -Restart |
Exchange 2013
1 2 |
Install-Wi |