Konsèp: Kesyon sou poechèl mande ki pi souvan.
Ou kapab sèvi ak lis sa a nan diferan fason:
- A kapab bay kopi / keratin kòmandman nan yon script
- Pou wè byen vit sentaks la nan yon lòd espesifik
- Pou amelyore konesans teknik ou
- Yo dekouvri nouvo kòmandman
- Pou prepare yon entèvyou travay
À |
Jiyè 02 2015
|
Otè | powershell-guru.com |
Sous | haitian-creole.powershell-guru.com |
Kategori |
75
|
Kesyon |
610
|
System
Ki jan yo detèmine vèsyon m ‘lan nan poechèl?
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 } |
Ki jan yo kouri poechèl nan yon lòt vèsyon pou bak konpatibilite?
powershell.exe -Version 2.0
Ki jan yo mande pou yon vèsyon poechèl minim (3.0 ak pi wo) nan yon script ak poechèl?
#Requires -Version 3.0
Ki jan yo mande pou privilèj administratif pou yon script ak poechèl?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Ki jan yo tcheke paramèt yo nan yon script ak poechèl?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Kòman ou kapab jwenn enfòmasyon pou itilizatè a kounye a ak poechèl?
[Security.Principal.WindowsIdentity]::GetCurrent()
Ki jan yo kreye, edite, ak Reload yon pwofil ak poechèl?
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 |
Ki jan yo fè yon pran yon poz nan 5 segonn / minit nan yon script ak poechèl?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Kòman ou kapab jwenn tan an bòt pase a ak poechèl?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Kòman ou kapab jwenn accélérateurs kalite ak poechèl?
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 |
Ki jan yo lis pwogram yo demaraj ak poechèl?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Ki jan yo unenstal yon aplikasyon ak poechèl?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Ki jan yo pran yon D nan Desktop la tout antye oswa nan yon fenèt aktif ak poechèl?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Kòman ou kapab jwenn konte a mesaj pou MSMQ ke moun kap kriye ak poechèl?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Kouman yo mete politik la ekzekisyon ak poechèl?
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 |
Ki jan yo kreye yon chemen kout ak poechèl?
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() |
Ki jan yo PIN oswa detache yon pwogram nan ekstrè an ak poechèl?
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
Ki jan yo louvri yon Explorer Windows ak poechèl?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Ki jan yo lis chofè aparèy ak poechèl?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Kouman yo kreye yon GUID ak poechèl?
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') |
Kòman ou kapab jwenn kote adrès la nan anyè a pou yon ti tan pou itilizatè a kounye a ak poechèl?
[System.IO.Path]::GetTempPath()
Ki jan yo rantre nan yon chemen ak yon chemen pitit nan yon sèl chemen sèl ak poechèl?
Join-Path -Path C:\ -ChildPath \windows
Ki jan yo lis tout kmdle “Get- *” ak poechèl?
Get-Command -Verb Get
Ki jan yo lis dosye sistèm espesyal ak poechèl?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Ki jan yo mòn ISO dosye / VHD ak poechèl?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Ki jan yo tcheke vèsyon .NET chapant enstale ak poechèl?
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 |
Ki jan yo tcheke si se vèsyon an NET chapant 4.5 enstale ak poechèl?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Ki jan yo kòmanse epi yo sispann yon relve nòt (yo kreye yon dosye nan sesyon-an Windows poechèl) ak poechèl?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Kouman chanje anyè aktyèl la nan yon kote espesifik ak poechèl?
Set-Location -Path 'C:\scripts'
Ki jan yo klè ekran an ak poechèl?
Clear-Host
cls # Alias
Kouman chanje rezolisyon an ekspozisyon ak poechèl?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Kouman yo mete “ekran plen” fenèt la ak poechèl?
mode.com 300
Kòman ou kapab jwenn dimansyon (lajè ak wotè) nan yon foto ak poechèl?
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 } |
Kòman ou kapab jwenn kle a pwodwi Windows ak poechèl?
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
Kòman ou kapab jwenn aktyèl “% Processor Tan an” (mwayèn) nan dènye 5 segonn yo (10 fwa) ak poechèl?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Ki jan yo chaje asanble ak poechèl?
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') |
Ki jan yo tcheke asanble .NET aktyèl chaje ak poechèl?
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
Ki jan yo jwenn (Cache Global Asanble) chemen an GAC ak poechèl?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Ki jan yo kopi rezilta nan papye a ak poechèl?
1 |
Get-Process | clip.exe |
Kòman ou kapab jwenn sa ki ekri nan papye a ak poechèl?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Kòman ou kapab jwenn korektif yo enstale ak poechèl?
Get-HotFix -ComputerName $computer
Kòman ou kapab jwenn korektif yo enstale avan / aprè yon dat espesifik ak poechèl?
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
Ki jan yo tcheke si se yon korektif enstale ak poechèl?
Get-HotFix -Id KB2965142
Kòman ou kapab jwenn korektif yo enstale sou yon òdinatè aleka ak poechèl?
Get-HotFix -ComputerName $computer
Pagefile
Kòman ou kapab jwenn enfòmasyon pagefile ak poechèl?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Kòman ou kapab jwenn gwosè a rekòmande (MB) pou pagefile la ak poechèl?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Kouman yo kreye yon pagefile (4096 MB) sou (D la 🙂 kondwi ak poechèl?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Ki jan yo efase yon pagefile sou (C a 🙂 kondwi ak poechèl?
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
Ki jan yo tcheke fwagmantasyon a nan yon kondwi ak poechèl?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Ki jan yo tcheke espas ki la ki gen kapasite nan kondui ak poechèl?
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
Ki jan yo louvri yon dosye ak poechèl?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Kouman li yon dosye ak poechèl?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Ki jan yo ekri pwodiksyon nan yon dosye ak poechèl?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
Kòman ou kapab jwenn fullname an nan dosye a script aktyèl ak poechèl?
$MyInvocation.MyCommand.Path
Ki jan yo konpresyon / dosye postal ak poechèl?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
Ki jan yo dekonprese / dosye ouvriers ak poechèl?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
Ki jan yo wè dosye yo nan yon achiv postal ak poechèl?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Ki jan yo montre gwosè a nan yon dosye ki nan KB ak poechèl?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Ki jan yo jwenn dosye pi gwo oswa mwens pase 1 GB ak poechèl?
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} |
Ki jan yo montre non an nan yon dosye san yo pa ekstansyon an ak poechèl?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Ki jan yo montre ekstansyon sa a nan yon dosye ak poechèl?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Ki jan yo jwenn vèsyon an dosye nan yon dosye ak poechèl?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Kòman ou kapab jwenn regle la nan yon dosye ak poechèl?
(Get-FileHash $file).Hash
Kòman ou kapab jwenn nan Controls MD5 / SHA1 nan yon dosye ak poechèl?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Ki jan yo montre dosye kache ak poechèl?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Ki jan yo tcheke si yon dosye gen yon ekstansyon ak poechèl?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Kouman yo mete yon dosye kòm “Read Se sèlman” ak poechèl?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Ki jan yo chanje “LastWriteTime” atribi nan semèn pase a pou yon dosye ak poechèl?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Ki jan yo kreye yon dosye nouvo ak poechèl?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Ki jan yo chanje non yon dosye ak poechèl?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Ki jan yo esansyèl / pakèt chanje non dosye miltip ak poechèl?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Ki jan yo efase yon dosye ak poechèl?
Remove-Item -Path 'C:\scripts\file.txt'
Ki jan yo montre 10 dènye liy yo nan yon dosye ak poechèl?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Ki jan yo dégager dosye plizyè nan yon katab ak poechèl?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Ki jan yo retire liy vid ki sòti nan yon dosye ak poechèl?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Ki jan yo tcheke si yon dosye ki egziste ak poechèl?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Kòman ou kapab jwenn dernye / pi ansyen dosye a ki te kreye nan yon katab ak poechèl?
1 2 |
Get-ChildItem | Sort-Object -Property CreationTime | Select-Object -Last 1 # Newest Get-ChildItem | Sort-Object -Property CreationTime | Select-Object -First 1 # Oldest |
Ki jan yo retire liy kopi ki sòti nan yon dosye ak poechèl?
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 |
Kòman ou kapab jwenn dosye kreye plis oswa mwens pase 1 mwa nan yon katab ak poechèl?
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 |
Kòman ou kapab jwenn dosye kreye plis oswa mwens pase 1 ane nan yon katab ak poechèl?
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 |
Ki jan yo ekspòtasyon valè a nan yon varyab nan yon dosye ak poechèl?
Set-Content -Path file.txt -Value $variable
Ki jan yo konte kantite dosye (* .txt) nan yon katab ak poechèl?
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 |
Ki jan yo rechèch yon fil andedan dosye miltip ak poechèl?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Ki jan yo montre premye / liy ki sot pase nan yon dosye ak poechèl?
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 |
Ki jan yo montre yon nimewo liy espesifik nan yon dosye ak poechèl?
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 |
Ki jan yo konte kantite liy nan yon dosye ak poechèl?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Ki jan yo konte kantite karaktè ak mo nan yon dosye ak poechèl?
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 |
Ki jan yo download yon dosye ak poechèl?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Ki jan yo montre chemen an plen nan yon dosye ak poechèl?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Ki jan yo kopi yon sèl dosye nan yon katab ak poechèl?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Ki jan yo kopi yon sèl dosye nan plizyè dosye ak poechèl?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Ki jan yo kopi dosye miltip nan yon sèl folder ak poechèl?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Ki jan yo jwenn serveurs Katalòg Global nan Anyè aktif ak poechèl?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Ki jan yo jwenn sit nan Anyè aktif ak poechèl?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Ki jan yo jwenn kontwolè nan domèn aktyèl ak poechèl?
(Get-ADDomainController).HostName
Ki jan yo jwenn tout contrôleur yo domèn nan yon domèn ak poechèl?
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} |
Ki jan yo jwenn echèk yo AD replikasyon ak poechèl?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
Ki jan yo jwenn tout lavi a onm pou forè a nan Anyè aktif ak poechèl?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Kòman ou kapab jwenn detay nan forè / domèn nan nan Anyè aktif ak poechèl?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Kòman ou kapab jwenn chemen an nan “efase objè” veso a nan Anyè aktif ak poechèl?
(Get-ADDomain).DeletedObjectsContainer
Ki jan yo ki ap pèmèt AD Resikle Bin karakteristik nan nan Anyè aktif ak poechèl?
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' |
Ki jan retabli yon kont AD soti nan Bin a Resikle nan Anyè aktif ak poechèl?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Ki jan yo jwenn wòl yo FSMO ak poechèl?
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 |
Ki jan pou konekte avèk yon kontwolè domèn espesifik ak poechèl?
Get-ADUser -Identity $user -Server 'serverDC01'
Kòman ou kapab jwenn sèvè a koneksyon aktyèl ak poechèl?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Ki jan yo fè “gpupdate” sou yon òdinatè ki gen poechèl?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Ki jan yo kreye yon gwoup nouvo nan Anyè aktif ak poechèl?
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' |
Ki jan yo retire yon gwoup nan Anyè aktif ak poechèl?
Remove-ADGroup -Identity 'PowershellGuru'
Ki jan yo ajoute yon itilizatè nan yon gwoup nan Anyè aktif ak poechèl?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Ki jan yo retire yon itilizatè soti nan yon gwoup nan Anyè aktif ak poechèl?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Ki jan yo jwenn gwoup vid (ki pa gen okenn manm) nan Anyè aktif ak poechèl?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Ki jan yo konte gwoup vid (ki pa gen okenn manm) nan Anyè aktif ak poechèl?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Kòman ou kapab jwenn manm yo nan yon gwoup nan Anyè aktif ak poechèl?
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' |
Kòman ou kapab jwenn manm yo nan yon gwoup ak manm repetitif nan Anyè aktif ak poechèl?
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
Kouman yo itilize yon generic an nan filtre a nan “Jwenn-ADUser” nan Anyè aktif ak poechèl?
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 |
Ki jan pou avanse pou pi yon itilizatè nan yon lòt OU nan Anyè aktif ak poechèl?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Ki jan yo jwenn tout manm yo ki (enbrike) pou yon itilizatè ak poechèl?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Kòman ou kapab jwenn manm yo (kout Non / twonke) pou yon itilizatè ak poechèl?
(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 |
Kouman chanje Deskripsyon nan, biwo, ak nimewo telefòn pou yon kont itilizatè nan Anyè aktif ak poechèl?
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 |
Ki jan yo déblotché yon kont itilizatè nan Anyè aktif ak poechèl?
Unlock-ADAccount $samAccountName
Ki jan yo ki ap pèmèt / enfim yon kont itilizatè nan Anyè aktif ak poechèl?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Ki jan yo retire yon kont itilizatè nan Anyè aktif ak poechèl?
Remove-ADUser $samAccountName
Ki jan yo Reyajiste yon modpas pou kont yon sèl itilizatè nan Anyè aktif ak poechèl?
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 |
Ki jan yo Reyajiste yon modpas pou plizyè kont itilizatè (esansyèl) nan Anyè aktif ak poechèl?
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 |
Ki jan yo jwenn mèt kay la nan yon dosye nan Anyè aktif ak poechèl?
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 |
Ki jan yo jwenn OU la (Inite òganizasyon) pou yon itilizatè nan Anyè aktif ak poechèl?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Ki jan yo jwenn kont itilizatè enfim nan Anyè aktif ak poechèl?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Ki jan yo jwenn kont itilizatè ekspire nan Anyè aktif ak poechèl?
Search-ADAccount -AccountExpired
Ki jan yo jwenn kont itilizatè fèmen nan Anyè aktif ak poechèl?
Search-ADAccount -LockedOut
Ki jan yo jwenn Sid la nan yon kont itilizatè nan Anyè aktif ak poechèl?
(Get-ADUser $user -Properties SID).SID.Value
Ki jan konvèti yon non itilizatè SID nan Anyè aktif ak poechèl?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Ki jan yo konvèti yon SID non itilizatè nan Anyè aktif ak poechèl?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
Kouman fann Non a Distenge nan yon kont itilizatè nan Anyè aktif ak poechèl?
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" |
Ki jan yo jwenn dat la nan kreyasyon / modifikasyon nan yon kont itilizatè nan Anyè aktif ak poechèl?
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 |
Kòman ou kapab jwenn chemen an ldap pou yon itilizatè nan Anyè aktif ak poechèl?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
Kouman chanje CN a (kanonik Non) pou yon itilizatè nan Anyè aktif ak poechèl?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Kòman ou kapab jwenn Inite nan òganizasyon (OU) paran nan yon itilizatè nan Anyè aktif ak poechèl?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
Kòman ou kapab jwenn mèt kay la nan yon itilizatè (ki te kreye kont la) nan Anyè aktif ak poechèl?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Kouman konvèti atribi nan PwdLastSet pou yon itilizatè nan Anyè aktif ak poechèl?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Ki jan yo teste kanal la sekirite ant òdinatè lokal la ak domèn nan ak poechèl?
Test-ComputerSecureChannel
Ki jan pou fè reparasyon pou kanal la sekirite ant òdinatè lokal la ak domèn nan ak poechèl?
Test-ComputerSecureChannel -Repair
Ki jan yo enfim yon kont òdinatè nan Anyè aktif ak poechèl?
Disable-ADAccount $computer
Ki jan yo jwenn òdinatè ak Sistèm espesifik Operating nan Anyè aktif ak poechèl?
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)
Kouman yo kreye yon Inite òganizasyon (OU) nan Anyè aktif ak poechèl?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Kòman ou kapab jwenn Inite òganizasyon (OU) detay nan Anyè aktif ak poechèl?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Kouman chanje deskripsyon an nan yon inite w la òganizasyon (OU) nan Anyè aktif ak poechèl?
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 |
Ki jan yo lis vid Inite òganizasyon (OUMENM) ak poechèl?
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 } |
Kòman ou kapab jwenn manadjè a nan yon gwoup ki gen poechèl?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Kòman yo ekstrè yon v4 adrès IP (80.80.228.8) ak Rjèks ak poechèl?
$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
Kòman yo ekstrè yon adrès MAC (C0-D9-62-39-61-2D) ak séparation “-” ak Rjèks ak poechèl?
$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
Kòman yo ekstrè yon adrès MAC (C0: D9: 62: 39: 61: 2D) ak séparation “:” ak Rjèks ak poechèl?
$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
Kòman yo ekstrè yon dat (10/02/2015) ak Rjèks ak poechèl?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Kòman yo ekstrè yon URL (www.powershell-guru.com) ak Rjèks ak poechèl?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Kòman yo ekstrè yon imèl (user@domain.com) ak Rjèks ak poechèl?
$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
Kòman yo ekstrè “Guru” nan egzanp lan fisèl ak Rjèks ak poechèl?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Kòman yo ekstrè “guru.com” nan egzanp lan fisèl ak Rjèks ak poechèl?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Kòman yo ekstrè “powershell-guru.com” nan egzanp lan fisèl ak Rjèks ak poechèl?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Kòman yo ekstrè “123” nan egzanp lan fisèl ak Rjèks ak poechèl?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Kòman yo ekstrè “$” (siy dola) soti nan egzanp lan fisèl ak Rjèks ak poechèl?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Ki jan yo ranplase yon karaktè (* .com) ak yon lòt (* .fr) nan yon fisèl ak Rjèks ak poechèl?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Ki jan yo sove yon afè ak Rjèks ak poechèl?
[regex]::Escape('\\server\share')
Memory
Ki jan yo fòse yon koleksyon memwa pa pèseptè a fatra ak poechèl?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Kòman ou kapab jwenn gwosè a RAM nan yon òdinatè ki gen poechèl?
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
Kòman ou kapab jwenn dat aktyèl la ak poechèl?
Get-Date
[Datetime]::Now
Ki jan yo montre dat la nan fòma diferan ak poechèl?
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 |
Ki jan konvèti yon dat (datetime) nan yon dat (fisèl) ak poechèl?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
Ki jan konvèti yon dat (fisèl) nan yon dat (datetime) ak poechèl?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
Kouman kalkile diferans lan (kantite jou, èdtan, minit, oswa segonn) ant de dat ak poechèl?
(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
Ki jan yo konpare de dat ak poechèl?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False
Ki jan yo sòt yon etalaj de dat kòm “datetime” ak poechèl?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Ki jan yo kòmanse epi yo sispann yon kronomètr ak poechèl?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Kòman ou kapab jwenn jou aktyèl la nan semèn nan ak poechèl?
(Get-Date).DayOfWeek #Sunday
Kòman ou kapab jwenn dat yè a ak poechèl?
(Get-Date).AddDays(-1)
Kòman ou kapab jwenn kantite jou nan yon mwa (nan mwa fevriye 2015) ak poechèl?
[DateTime]::DaysInMonth(2015, 2)
Ki jan yo konnen yon ane kwasans ak poechèl?
[DateTime]::IsLeapYear(2015)
Ki jan yo lis zòn tan ak poechèl?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Ki jan yo programme (nan fòma ASCII) ak dekode yon URL ak poechèl?
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 |
Ki sa ki ekivalan yo nan kòmandman rezo natif natal ak poechèl?
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 |
Kòman ou kapab jwenn adrès IP ak poechèl?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Ki jan yo enfim adrès IP V6 (IPV6) ak poechèl?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Ki jan yo valide yon adrès IP v4 (IPv4) ak poechèl?
if([ipaddress]'10.0.0.1'){'validated'}
Ki jan yo jwenn adrès IP nan ekstèn ak poechèl?
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 } |
Ki jan yo jwenn ot la soti nan yon adrès IP ak poechèl?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Ki jan yo jwenn adrès la IP ki sòti nan yon ot ak poechèl?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Ki jan yo jwenn FQDN a soti nan yon ot ak poechèl?
[System.Net.Dns]::GetHostByName($computer).HostName
Ki jan yo jwenn configuration la, te rezo (Ip, subne, Gateway, ak dns) ak poechèl?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Ki jan yo jwenn adrès la MAC ak poechèl?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Ki jan yo ping yon konpitè ki gen poechèl?
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) |
Ki jan yo tcheke si se yon òdinatè ki konekte nan entènèt la ak poechèl?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Ki jan yo fè yon “wwa” Passage pou yon sit entènèt ak poechèl?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Kòman ou kapab jwenn detay yo de yon IP piblik (Geolocation) ak poechèl?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Ki jan yo tcheke si yon pò a louvri / fèmen ak poechèl?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Ki jan yo fè “trasèr” ak poechèl?
Test-NetConnection www.google.com -TraceRoute
Ki jan yo ranje yon rezo lakay pwofil koneksyon avèk poechèl?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Ki jan yo montre koneksyon ki pò tchp ak poechèl?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Ki jan yo diminye yon URL long nan yon URL ti ak poechèl?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Kòman ou kapab jwenn anviwònman prokurasyon ak poechèl?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Ki jan yo tcheke kachèt a dns sou yon òdinatè lokal yo ak poechèl?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Ki jan yo klè yon kachèt dns sou yon òdinatè lokal yo ak poechèl?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Ki jan yo klè yon kachèt dns sou òdinatè aleka ak poechèl?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Kouman li gen tout pouvwa a yo ranpli ak poechèl?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Ki jan yo jenere yon modpas o aza ak poechèl?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Ki jan yo chanje modpas la lokal yo, pou yon administratè sou yon sèvè aleka ak poechèl?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Ki jan yo jwenn dat ekspirasyon an modpas nan yon kont nan Anyè aktif ak poechèl?
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
Ki jan yo lis tout enprimant yo pou yon sèvè espesifik ak poechèl?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Ki jan yo lis tout pò yo pou yon sèvè espesifik ak poechèl?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Kouman chanje kòmantè / kote adrès la nan yon printer ak poechèl?
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() |
Ki jan fè detwi (anile tout travay) nan yon printer ak poechèl?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Ki jan yo enprime yon paj tès pou yon printer ak poechèl?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Kòman ou kapab jwenn ke moun kap kriye ekri an lèt detache pou enprimant ak poechèl?
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
Ki jan yo lis itikè rejis ak poechèl?
Get-ChildItem -Path Registry::
Kòman ou kapab jwenn valè rejis ak kalite valè ak poechèl?
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) } } } |
Ki jan yo lis rejis kle subkeys ak poechèl?
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:\' |
Ki jan yo lis subkeys kle rejis nan yon fason repetitif ak poechèl?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Ki jan yo jwenn subkeys ak yon non espesifik ak poechèl?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Ki jan yo retounen sèlman non an nan subkeys yo rejis ak poechèl?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Ki jan yo lis valè rejis ak poechèl?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Kouman li yon valè rejis espesifik ak poechèl?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Kouman li yon valè rejis espesifik sou yon òdinatè aleka ak poechèl?
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
Ki jan yo kreye yon nouvo kle rejis ak poechèl?
New-Item -Path 'HKCU:\Software\MyApplication'
Ki jan yo kreye yon valè rejis ak poechèl?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Ki jan li modifye yon valè rejis ki ekziste yo ak poechèl?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Ki jan yo efase yon valè rejis ak poechèl?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Ki jan yo efase yon kle rejis ak poechèl?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Ki jan yo teste si yon kle rejis egziste ak poechèl?
Test-Path -Path 'HKCU:\Software\MyApplication'
Ki jan yo teste si se yon valè rejis egziste ak poechèl?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Ki jan yo retire karaktè blan-espas soti nan konmansman an nan yon fisèl ak poechèl?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Ki jan yo retire karaktè blan-espas soti nan fen a nan yon fisèl ak poechèl?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Ki jan yo retire karaktè blan-espas (kòmanse epi ki fini) nan yon fisèl ak poechèl?
$string = ' PowershellGuru '
$string = $string.Trim()
Ki jan konvèti yon fisèl nan dosye anwo yo tou ak poechèl?
$string = 'powershellguru'
$string = $string.ToUpper()
Ki jan konvèti yon fisèl pi ba ka ak poechèl?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Ki jan yo ka chwazi chèn “poechèl nan” nan fisèl la “PowerShellGuru” ak poechèl?
$string.Substring(0,10)
Ki jan yo ka chwazi chèn nan “Guru” nan fisèl la “PowerShellGuru” ak poechèl?
$string.Substring(10)
Ki jan yo chwazi nimewo ki “123” nan “PowerShell123Guru” ak poechèl?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Kòman ou kapab jwenn endèks a zewo ki baze sou nan “Guru” nan fisèl “PowerShellGuru la” ak poechèl?
$string.IndexOf('Guru') # 10
Ki jan yo tcheke si yon fisèl se nil oswa vid yo avèk poechèl?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Ki jan yo tcheke si yon fisèl se nil, vid, oswa konsiste sèlman nan karaktè blan-espas ak poechèl?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Ki jan yo tcheke si yon fisèl gen yon lèt espesifik ak poechèl?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Ki jan yo retounen longè yon fisèl ak poechèl?
$string.Length
Ki jan yo anchene de strings ak poechèl?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Ki jan yo matche ak pou youn oswa plizyè parantèz “[]” nan yon fisèl ak poechèl?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Ki jan yo matche ak pou youn oswa plizyè parantèz “()” nan yon fisèl ak poechèl?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Ki jan yo matche ak pou youn oswa plizyè parantèz Curly “{}” nan yon fisèl ak poechèl?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Ki jan yo matche ak pou youn oswa plizyè parantèz ang “<>” nan yon fisèl ak poechèl?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Ki jan yo matche ak nenpòt lèt miniskil (abc) nan yon fisèl ak poechèl?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Ki jan yo matche ak nenpòt upperletters (ABC) nan yon fisèl ak poechèl?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Ki jan yo matche ak “[p” (p pi ba a) nan yon fisèl ak poechèl?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Ki jan yo matche ak “[P” (P anwo a) nan yon fisèl ak poechèl?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Ki jan yo ranplase yon liy ak yon lòt liy ak poechèl?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Ki jan konvèti yon operasyon divizyon nan yon fisèl (pousantaj) ak poechèl?
(1/2).ToString('P')
Ki jan yo sòt strings ki gen nimewo ak poechèl?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Ki jan yo chwazi dènye mo a nan yon fraz ak poechèl?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Ki jan yo ka resevwa pawòl Bondye a pi gwo nan yon fraz ak poechèl?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Ki jan yo konte kantite fwa yon fisèl ki prezan nan yon fraz ak poechèl?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Ki jan yo kopi chak karaktè nan yon fisèl nan yon etalaj karaktè ak poechèl?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Kouman konvèti premye lèt nan majuskul nan yon fisèl ak poechèl?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Ki jan yo pad (gòch la oswa dwa) yon afè ak poechèl?
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 |
Ki jan yo programme ak dekode yon fisèl Base64 ak poechèl?
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 |
Ki jan yo konvèti yon nimewo (pou ale ak pou soti nan) binè ak poechèl?
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) |
Ki jan yo retounen sèlman folder nan paran sot pase a nan yon chemen ak poechèl?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Ki jan yo retounen sèlman dènye atik la nan yon chemen ak poechèl?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Ki jan yo lis metòd yo nan klas la System.Math ak poechèl?
[System.Math] | Get-Member -Static -MemberType Method
Ki jan yo retounen valè a absoli ak poechèl?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Ki jan yo retounen ang lan ki gen san se nimewo a espesifye ak poechèl?
[Math]::ASin(1) #Returns 1,5707963267949
Ki jan yo retounen valè a plafon ak poechèl?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Ki jan yo retounen valè a etaj ak poechèl?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Ki jan yo retounen natirèl (baz e) logaritm a nan yon nimewo ki espesifye ak poechèl?
[Math]::Log(4) #Returns 1,38629436111989
Ki jan yo retounen logaritm a baz 10 nan yon nimewo ki espesifye ak poechèl?
[Math]::Log10(4) #Returns 0,602059991327962
Ki jan yo retounen maksimòm la nan de valè ak poechèl?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Ki jan yo retounen minimòm la nan de valè ak poechèl?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Ki jan yo retounen yon nimewo leve soti vivan nan yon pouvwa espesifye ak poechèl?
[Math]::Pow(2,4) #Returns 16
Ki jan yo retounen yon valè desimal ki pi pre valè a entegral ak poechèl?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Ki jan yo retounen yon pati nan entegral nan yon nimewo desimal espesifye ak poechèl?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Ki jan yo retounen rasin kare yon nimewo ki espesifye ak poechèl?
[Math]::Sqrt(16) #Returns 4
Ki jan yo retounen konstan nan PI ak poechèl?
[Math]::Pi #Returns 3,14159265358979
Ki jan yo retounen baz natirèl la logaritmik (konstan e) ak poechèl?
[Math]::E #Returns 2,71828182845905
Ki jan yo tcheke si yon nonb se menm oswa enpè ak poechèl?
[bool]($number%2)
Hashtables
Kouman yo kreye yon hashtable vid yo avèk poechèl?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Kouman yo kreye yon hashtable ak atik ak poechèl?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
Kouman yo kreye yon hashtable Ranje pa kle / Non (diksyonè te bay lòd) ak atik ak poechèl?
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
Ki jan yo ajoute atik (kle-valè pè) nan yon hashtable ak poechèl?
$hashtable.Add('Key3', 'Value3')
Kòman ou kapab jwenn yon valè espesifik nan yon hashtable ak poechèl?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Kòman ou kapab jwenn valè a minimòm de yon hashtable ak poechèl?
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 |
Kòman ou kapab jwenn valè a maksimòm de yon hashtable ak poechèl?
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 |
Ki jan li modifye atik ki nan yon hashtable ak poechèl?
$hashtable.Set_Item('Key1', 'Value1Updated')
Ki jan yo retire atik ki nan yon hashtable ak poechèl?
$hashtable.Remove('Key1')
Ki jan yo klè yon hashtable ak poechèl?
$hashtable.Clear()
Ki jan yo tcheke prezans nan yon kle / valè espesifik nan yon hashtable ak poechèl?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Ki jan yo sòt pa kle / valè nan yon hashtable ak poechèl?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Ki jan yo kreye yon etalaj vid yo avèk poechèl?
$array = @()
$array = [System.Collections.ArrayList]@()
Ki jan yo kreye yon etalaj ak atik ak poechèl?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Ki jan yo ajoute atik yo yon etalaj ak poechèl?
$array += 'D'
[void]$array.Add('D')
Ki jan li modifye yon atik nan yon etalaj ak poechèl?
$array[0] = 'Z' # 1st item[0]
Ki jan yo tcheke gwosè a nan yon etalaj ak poechèl?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Ki jan yo rekipere yon atik / plizyè / tout bagay nan yon etalaj ak poechèl?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Ki jan yo retire atik vid nan yon etalaj ak poechèl?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Ki jan yo tcheke si yon atik ki egziste nan yon etalaj ak poechèl?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Ki jan yo jwenn nimewo a endèks nan yon atik nan yon etalaj ak poechèl?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Ki jan yo ranvèse lòd la nan atik nan yon etalaj ak poechèl?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Ki jan yo jenere yon atik o aza soti nan yon etalaj ak poechèl?
$array | Get-Random
Ki jan yo sòt yon etalaj nan yon / fason desann moute ak poechèl?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Ki jan yo konte kantite atik nan yon etalaj ak poechèl?
$array.Count
Ki jan yo ajoute yon etalaj nan yon lòt ak poechèl?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Ki jan yo jwenn Doublon soti nan yon etalaj ak poechèl?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
Ki jan yo retire Doublon soti nan yon etalaj ak poechèl?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
Ki jan yo kreye yon etalaj ak atik kòmanse avèk yon prefiks (“user01”, “user02”, … “user10”) ak poechèl?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Ki jan yo lis akl nan yon itilizatè AD ak poechèl?
(Get-Acl -Path "AD:\$dn").Access
Ki jan yo lis akl nan yon folder ak poechèl?
(Get-Acl -Path C:\scripts).Access
Ki jan yo lis espesifik akl pèmisyon antre (itilizatè oswa gwoup) nan yon itilizatè AD ak poechèl?
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
Ki sa ki kalite yo done ki pi komen ak poechèl?
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 |
Ki jan yo jwenn minimòm la ak valè maksimòm pou kèk varyab kalite ak poechèl?
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 |
Ki jan yo teste datatip a ak poechèl?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
Kouman yo kreye yon Isit la-fisèl varyab ak poechèl?
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} "@ |
Ki jan yo kreye yon varyab ak poechèl?
$powershellGuru = 'Hello'
Ki jan yo kreye yon varyab konstan ak poechèl?
Set-Variable -Name powershellGuru -Value 2015 -Option Constant
Ki jan yo kreye yon varyab mondyal ak poechèl?
$Global:powershellGuru = 'Hello'
Kouman li yon varyab ak poechèl?
$powershellGuru = 'Hello' # Create
$powershellGuru # Read