概念 : PowerShell中最常見的問題。
您可以用不同的方式使用此列表 :
- 複製/貼上指令到腳本
- 快速查看特定指令的語法
- 改善你的專業知識
- 發現新的指令
- 為工作準備面試
更新 |
2015年10月7日
|
筆者 | powershell-guru.com |
資料來源 | chinese-traditional.powershell-guru.com |
分類 |
75
|
問題 |
610
|
System
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 } |
如何在另一個版本向後兼容執行PowerShell?
powershell.exe -Version 2.0
如何使用PowerShell,在脚本中要求最小的PowerShell版本(3.0或更高)?
#Requires -Version 3.0
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
如何使用PowerShell檢查腳本的參數?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
如何使用PowerShell取得現時用戶的資料?
[Security.Principal.WindowsIdentity]::GetCurrent()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Check if a profile exists Test-Path -Path $PROFILE # Current User,Current Host Test-Path -Path $PROFILE.CurrentUserCurrentHost # Current User,Current Host Test-Path -Path $PROFILE.CurrentUserAllHosts # Current User,All Hosts Test-Path -Path $PROFILE.AllUsersCurrentHost # All Users, Current Host Test-Path -Path $PROFILE.AllUsersAllHosts # All Users, All Hosts # Create a new profile for current user New-Item -ItemType File -Force $PROFILE # CurrentUserCurrentHost New-Item -ItemType File -Force $PROFILE.CurrentUserCurrentHost New-Item -ItemType File -Force $PROFILE.CurrentUserAllHosts # Edit psEdit $PROFILE (only for ISE) ise $PROFILE (only for ISE) notepad.exe $PROFILE # Reload (without restarting Powershell) & $PROFILE .$PROFILE # List profiles $PROFILE | Format-List * -Force |
如何使用PowerShell,在腳本處理5秒鐘/分鐘的停頓?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
如何使用PowerShell取得最後的開機時間?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
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 |
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
如何使用PowerShell螢幕截圖整個桌面或當前窗口?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
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 |
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() |
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
如何使用PowerShell打開檔案總管?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
如何使用PowerShell列出設備驅動程序?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Empty GUID [GUID]::Empty 00000000-0000-0000-0000-000000000000 # New GUID (lower case by default) [GUID]::NewGuid() 7049b4a9-e4bc-4008-a683-067934bd39cf # New GUID (upper case) $guid = ([GUID]::NewGuid()).ToString().ToUpper() DD7F5A7B-F46B-49D0-B8A1-D8D1360D2E27 # New GUID with a specific value [GUID]('bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7') bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7 # New GUID (Powershell v5) New-Guid cdcaa4d9-c85f-40d7-afd9-32f003afa130 |
如何使用PowerShell取得當前用戶的臨時目錄位置?
[System.IO.Path]::GetTempPath()
如何使用PowerShell將路徑和子路徑連成為一個單一的路徑?
Join-Path -Path C:\ -ChildPath \windows
如何使用PowerShell列出所有cmdlet的“Get- *”?
Get-Command -Verb Get
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
如何使用PowerShell安裝ISO/VHD文件?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
如何使用PowerShell檢查已安裝的.NET Framework版本?
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 |
如何使用PowerShell檢查 .NET Framework 4.5版本中是否已安裝?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
如何使用PowerShell啟動和停止轉錄(建立Windows PowerShell會話的記錄)?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
如何使用PowerShell更改當前目錄至一個特定的位置?
Set-Location -Path 'C:\scripts'
如何使用PowerShell清除屏幕?
Clear-Host
cls # Alias
如何使用PowerShell改變螢幕的解析度?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
如何使用PowerShell設置“全屏顯示”窗口?
mode.com 300
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 } |
如何使用PowerShell取得Windows的產品安裝序號?
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
如何使用PowerShell取得5秒前(10次)的目前(平均)“%處理器時間”?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
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') |
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
如何使用PowerShell尋找GAC(全域組件快取)的路徑?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
1 |
Get-Process | clip.exe |
如何使用PowerShell取得剪貼簿中的內容?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
如何使用PowerShell取得已安裝的修復程序?
Get-HotFix -ComputerName $computer
如何使用PowerShell在特定日期前/後安裝修復程序?
Get-HotFix | Where-Object -FilterScript { $_.InstalledOn -lt ([DateTime]'01/01/2015') } # Before 01/01/2015
Get-HotFix | Where-Object -FilterScript {$_.InstalledOn -gt ([DateTime]'01/01/2015')} # After 01/01/2015
如何使用PowerShell檢查修復程序是否已安裝?
Get-HotFix -Id KB2965142
如何使用PowerShell在遠程電腦上安裝修補程序?
Get-HotFix -ComputerName $computer
Pagefile
如何使用PowerShell取得Pagefile的資料?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
如何使用PowerShell取得Pagefile的大小推薦(MB)?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
如何使用PowerShell在驅動器(D:)建立一個Pagefile(4096 MB)?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
如何使用PowerShell刪除驅動器(C:)的Pagefile?
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
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
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
如何使用PowerShell開啟文件?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
如何使用PowerShell閱讀文件?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
1 2 3 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt' -Encoding ascii 'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt 'Line1', 'Line2', 'Line3' > file.txt |
如何使用PowerShell取得當前腳本的全名?
$MyInvocation.MyCommand.Path
1 2 3 4 5 6 7 8 9 10 11 12 13 |
### COMPRESS ONE FILE ### # Powershell v5 Compress-Archive -Path $fileSource -DestinationPath $fileDestination ### COMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::CreateFromDirectory($folderSource,$fileDestination) # Powershell v5 Compress-Archive -Path $folderSource -DestinationPath $fileDestination |
1 2 3 4 5 6 7 8 9 10 |
### UNCOMPRESS ONE FILE ### # Powershell v5 Expand-Archive -Path $fileSource -DestinationPath $folderDestination ### UNCOMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::ExtractToDirectory($fileSource, $folderDestination) |
如何使用PowerShell查看ZIP存檔中的文件?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
如何使用PowerShell顯示文件的大小(KB)?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
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} |
如何使用PowerShell顯示不帶擴展名的的文件名稱?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
如何使用PowerShell顯示文件的擴展名稱?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
如何使用PowerShell取得文件的 “hash”?
(Get-FileHash $file).Hash
如何使用PowerShell取得文件的MD5 / SHA1校驗值?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
如何使用PowerShell設置文件為“唯讀”?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
如何使用PowerShell更改文件的“LastWriteTime”(最後寫入時間)屬性為上週?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
如何使用PowerShell建立一個新的文件?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
如何使用PowerShell重新命名文件?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
如何使用PowerShell大量/成批的重新命名多個文件?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
如何使用PowerShell刪除文件?
Remove-Item -Path 'C:\scripts\file.txt'
如何使用PowerShell顯示文件的最新10行?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
如何使用PowerShell解除文件夾的數個文件?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
如何使用PowerShell刪除文件中空行?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
如何使用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 |
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 |
如何使用PowerShell取得文件夾中建立多或少於1個月的文件?
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 |
如何使用PowerShell取得文件夾中建立多或少於1個年的文件?
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 |
如何使用PowerShell將變數值輸出?
Set-Content -Path file.txt -Value $variable
如何使用PowerShell計算文件夾中的文件(*.txt)的數量??
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 |
如何使用PowerShell在多個文件中搜索字符串?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
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 |
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 |
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
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 |
如何使用PowerShell下載文件?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
如何使用PowerShell顯示文件的完整路徑?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
如何使用PowerShell複製一個文件到文件夾?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
如何使用PowerShell複製多個文件到一個文件夾?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
如何使用PowerShell在活動目錄(Active Directory)尋找通用類別目錄 (Global Catalog servers)?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
如何使用PowerShell尋找活動目錄(Active Directory)的網站?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
1 2 3 4 5 6 7 8 9 10 |
(Get-ADDomainController).HostName # Solution 1 $env:LOGONSERVER # Solution 2 [System.Environment]::GetEnvironmentVariable('logonserver') # Solution 3 nltest.exe /dsgetdc:domain.com |
1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 (Get-ADDomainController -Filter *).Name # Solution 2 (Get-ADGroupMember 'Domain Controllers').Name # Solution 3 ((Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))')).Name # Solution 4 ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).DomainControllers.Name |
如何使用PowerShell尋找AD複製故障?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
如何使用PowerShell尋找活動目錄(Active Directory)的樹系之下墓碑時間?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
如何使用PowerShell取得活動目錄(Active Directory)林/域中的詳細信息?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
如何使用PowerShell取得活動目錄(Active Directory)“已刪除項目”垃圾桶的路徑?
(Get-ADDomain).DeletedObjectsContainer
如何使用PowerShell啟用活動目錄(Active Directory)中的AD回收站功能?
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' |
如何使用PowerShell恢復活動目錄(Active Directory)回收站的AD帳戶?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
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 |
如何使用PowerShell連接到一個特定的網域控制站?
Get-ADUser -Identity $user -Server 'serverDC01'
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
如何使用PowerShell在電腦上進行“gpupdate”?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
如何使用PowerShell建立活動目錄(Active Directory)的新群組?
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' |
如何使用PowerShell刪除活動目錄(Active Directory)群組?
Remove-ADGroup -Identity 'PowershellGuru'
如何使用PowerShell新增用戶到活動目錄(Active Directory)群組?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
如何使用PowerShell刪除活動目錄(Active Directory)群組的用戶?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
如何使用PowerShell尋找活動目錄(Active Directory)空群組(沒任何成員)?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
如何使用PowerShell計算活動目錄(Active Directory)空群組(沒任何成員)的數目?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
如何使用PowerShell取得活動目錄(Active Directory)群組的成員?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Solution 1 (Get-ADGroupMember 'Powershell Guru').DistinguishedName (Get-ADGroupMember 'Powershell Guru').Samaccountname # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
如何使用PowerShell取得活動目錄(Active Directory)群組遞歸成員?
1 2 |
(Get-ADGroupMember 'Powershell Guru' -Recursive).DistinguishedName (Get-ADGroupMember 'Powershell Guru' -Recursive).Samaccountname |
如何使用PowerShell計算活動目錄(Active Directory)群組的成員有/沒有遞歸成員?
1 2 |
(Get-ADGroupMember 'Powershell Guru' | Select-Object -ExpandProperty Samaccountname).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | Select-Object -ExpandProperty Samaccountname).Count |
Users
如何使用PowerShell在活動目錄(Active Directory)使用“GET-ADUser”過濾通配?
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 |
如何使用PowerShell在活動目錄(Active Directory)中將用戶轉移到另一個OU?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
如何使用PowerShell尋找所有(Nested嵌套)的成員的用戶?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
如何使用PowerShell為用戶取得會員的(簡稱/截斷)?
(Get-ADUser -Identity $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object
如何使用PowerShell為活動目錄(Active Directory)中的用戶賬號重新命名名稱(全名),(顯示名稱),指定人名(名字)和姓(姓氏)?
1 2 |
Set-ADUser $samAccountName -DisplayName 'DisplayName' -GivenName 'Test' -Surname 'Powershell' -DisplayName 'Test Powershell' Rename-ADObject $dn -NewName 'Test Powershell' #FullName |
如何使用PowerShell為活動目錄(Active Directory)中的用戶賬號更改描述,辦公室,以及電話號碼?
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'
如何使用PowerShell為活動目錄(Active Directory)中的用戶賬號設置失效日期“31/12/2015”或“從不”?
1 2 3 4 5 |
# 31/12/2015 Set-ADAccountExpiration $samAccountName -DateTime '01/01/2016' # Never Clear-ADAccountExpiration $samAccountName |
如何使用PowerShell為活動目錄(Active Directory)中的用戶賬號解除鎖定?
Unlock-ADAccount $samAccountName
如何使用PowerShell啟用/禁用活動目錄(Active Directory)的用戶帳戶?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
如何使用PowerShell刪除活動目錄(Active Directory)的用戶帳戶?
Remove-ADUser $samAccountName
如何使用PowerShell重置活動目錄(Active Directory)的用戶帳戶密碼?
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 |
如何使用PowerShell重置活動目錄(Active Directory)多個用戶帳戶(散裝)的密碼?
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 |
如何使用PowerShell尋找活動目錄(Active Directory)中的文件主人?
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 |
如何使用PowerShell尋找活動目錄(Active Directory)的用戶 OU(組織單位)?
[regex]::match("$((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
如何使用PowerShell尋找活動目錄(Active Directory)禁用的用戶帳戶?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
如何使用PowerShell尋找活動目錄(Active Directory)過期的用戶帳戶?
Search-ADAccount -AccountExpired
如何使用PowerShell尋找活動目錄(Active Directory)鎖定的用戶帳戶?
Search-ADAccount -LockedOut
如何使用PowerShell尋找活動目錄(Active Directory)SID的用戶帳戶?
(Get-ADUser -Identity $user -Properties SID).SID.Value
如何使用PowerShell在活動目錄(Active Directory)將使用者名稱轉換為SID?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
如何使用PowerShell在活動目錄(Active Directory)將用SID轉換為使用者名稱?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
如何使用PowerShell在活動目錄(Active Directory)分割用戶帳戶的專有名稱?
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" |
如何使用PowerShell在活動目錄(Active Directory)尋找用戶帳戶的建立/修改日期?
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated
如何使用PowerShell在活動目錄(Active Directory) 顯示“用戶”種類的可選性和強制性的特性?
1 2 3 |
$schema = [DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema() $schema.FindClass('user').mandatoryproperties | Format-Table $schema.FindClass('user').optionalproperties | Format-Table |
如何使用PowerShell在活動目錄(Active Directory) 取得LDAP路徑?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
如何使用PowerShell在活動目錄(Active Directory) 改變用戶的CN(正準名稱)?
Rename-ADObject $((Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
如何使用PowerShell在活動目錄(Active Directory) 取得用戶組織單位(OU)的父層?
1 2 |
$dn = (Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
如何使用PowerShell在活動目錄(Active Directory)取得用戶建立人(帳戶建立人)?
1 2 |
$dn = (Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
如何使用PowerShell在活動目錄(Active Directory)轉換用戶的pwdLastSet屬性?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
如何使用PowerShell測試本地電腦和域名之間的安全通道?
Test-ComputerSecureChannel
如何使用PowerShell修復本地電腦和域名之間的安全通道?
Test-ComputerSecureChannel -Repair
如何使用PowerShell在活動目錄(Active Directory)禁用電腦帳戶?
Disable-ADAccount $computer
如何使用PowerShell在活動目錄(Active Directory)尋找特定操作系統的電腦?
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)
如何使用PowerShell在活動目錄(Active Directory)建立一個組織單位(OU)?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
如何使用PowerShell在活動目錄(Active Directory)取得組織單位(OU)的詳細信息?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
如何使用PowerShell在活動目錄(Active Directory)更改組織單位(OU)的描述?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
如何使用PowerShell啟用/禁用活動目錄(Active Directory)組織單位(OU)的意外刪除?
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 |
如何使用PowerShell啟用活動目錄(Active Directory)所有組織單位(OU)的意外刪除?
1 |
Get-ADOrganizationalUnit -Filter * -Property ProtectedFromAccidentalDeletion | Where-Object -FilterScript { $_.ProtectedFromAccidentalDeletion -eq $false } | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true |
如何使用PowerShell刪除在活動目錄(Active Directory)意外保護的組織單位(OU)?
1 2 |
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false Remove-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' |
如何使用PowerShell在活動目錄(Active Directory)轉換組織單位(OU)的專有名稱至正準名稱?
1 2 |
$parent = $dn.Split(',',2)[1] $parent = (Get-ADOrganizationalUnit $parent -Properties CanonicalName).CanonicalName |
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 } |
如何使用PowerShell取得群組管理者?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
如何使用PowerShell取得正則表達式的IP地址V4(80.80.228.8)?
$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
如何使用PowerShell提取正則表達式的 MAC地址(C0-D9-62-39-61-2D)與分隔符 “-”?
$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
如何使用PowerShell提取正則表達式的 MAC地址(C0:D9:62:39:61:2D)與分隔符 “:”?
$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
如何使用PowerShell提取正則表達式的日期 (10/02/2015)?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
如何使用PowerShell提取正則表達式的URL(www.powershell-guru.com)?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
如何使用PowerShell提取正則表達式的電子郵件(user@domain.com)?
$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
如何使用PowerShell提取正則表達式的字符串例如“guru”?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
如何使用PowerShell提取正則表達式的字符串例如“guru.com”?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
如何使用PowerShell提取正則表達式的字符串例如“powershell-guru.com”?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
如何使用PowerShell提取正則表達式的字符串例如“123”?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
如何使用PowerShell提取正則表達式的字符串例如“$”(貨幣符號)?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
如何使用PowerShell更換正則表達式字符串的一個字符(*.com)至另一個字符(*.fr)?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
如何使用PowerShell逃脫正則表達式的一個字符串?
[regex]::Escape('\\server\share')
Memory
如何使用PowerShell透過垃圾回收作強制記憶的收藏?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
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
如何使用PowerShell取得當前日期?
Get-Date
[Datetime]::Now
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
### DATETIME ### Get-Date -Format D : Tuesday, June 30, 2015 Get-Date -Format f : Tuesday, June 30, 2015 3:22 PM Get-Date -Format F : Tuesday, June 30, 2015 3:22:58 PM Get-Date -Format g : 6/30/2015 3:23 PM Get-Date -Format G : 6/30/2015 3:23:30 PM Get-Date -DisplayHint Date : Tuesday, June 30, 2015 Get-Date -DisplayHint DateTime : Tuesday, June 30, 2015 3:31:21 PM ### DATE ### Get-Date -Format d : 6/30/2015 Get-Date -Format yyyyMMdd : 20150630 Get-Date -UFormat '%d%m%Y' : 30062015 Get-Date -UFormat '%m%d%Y' : 06302015 Get-Date -UFormat '%Y%m%d' : 20150630 Get-Date -UFormat '%d.%m.%Y' : 30.06.2015 Get-Date -UFormat '%m.%d.%Y' : 06.30.2015 Get-Date -UFormat '%Y.%m.%d' : 2015.06.30 Get-Date -UFormat '%d-%m-%Y' : 30-06-2015 Get-Date -UFormat '%m-%d-%Y' : 06-30-2015 Get-Date -UFormat '%Y-%m-%d' : 2015-06-30 Get-Date -UFormat '%d/%m/%Y' : 30/06/2015 Get-Date -UFormat '%m/%d/%Y' : 06/30/2015 Get-Date -UFormat '%Y/%m/%d' : 2015/06/30 ### HOUR ### Get-Date -Format t : 3:23 PM Get-Date -Format T : 3:23:30 PM Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 28 (Minute) Get-Date -Format ss : 30 (Seconds) Get-Date -DisplayHint Time : 3:23:30 PM ### DAY ### Get-Date -Format dddd : Tuesday Get-Date -Format ddd : Tue Get-Date -Format dd : 30 ### MONTH ### Get-Date -Format MMMM : June Get-Date -Format MMM : Jun Get-Date -Format MM : 06 ### YEAR ### Get-Date -Format yyyy : 2015 |
如何使用PowerShell轉換日期(日期時間)至日期(字符串)?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 $datetimeToString = '{0:MM/dd/yy}' -f (Get-Date '07/15/2015') # Solution 2 $datetimeToString = (Get-Date '07/15/2015').ToShortDateString() # Check $datetimeToString 07/15/15 $datetimeToString.GetType().Name String |
如何使用PowerShell轉換日期(字符串)至日期(日期時間)?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Solution 1 $stringToDatetime = '07/15/2015' | Get-Date $stringToDatetime = '07-15-2015' | Get-Date # Solution 2 [Datetime]::ParseExact('07/15/2015', 'MM/dd/yyyy', $null) # Solution 3 $stringToDatetime = [Datetime]'7/15/2015' # Check $stringToDatetime Wednesday, July 15, 2015 12:00:00 AM $stringToDatetime.GetType().Name Datetime |
如何使用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
如何使用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
如何使用PowerShell排序數組的日期為“Datetime”?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
如何使用PowerShell啟動和停止計時秒器?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
如何使用PowerShell取得本周的當前日期?
(Get-Date).DayOfWeek #Sunday
如何使用PowerShell取得昨日的日期?
(Get-Date).AddDays(-1)
如何使用PowerShell取得某月份(2015年2月)的天數?
[DateTime]::DaysInMonth(2015, 2)
如何使用PowerShell知道是否閏年?
[DateTime]::IsLeapYear(2015)
如何使用PowerShell列出時區?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
如何使用PowerShell將URL編碼(以ASCII格式)和解碼?
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 |
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 |
如何使用PowerShell取得IP地址?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
如何使用PowerShell驗證IP地址V4(IPv4)?
if([ipaddress]'10.0.0.1'){'validated'}
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 } |
如何使用PowerShell尋找IP地址的主機名?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
如何使用PowerShell尋找主機名的IP地址?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
如何使用PowerShell尋找主機名的FQDN?
[System.Net.Dns]::GetHostByName($computer).HostName
如何使用PowerShell尋找網絡配置(IP,子網,網關和DNS)?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
如何使用PowerShell尋找MAC的地址?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
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) |
如何使用PowerShell檢查一部電腦是否已連接到互聯網?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
如何使用PowerShell執行網站的“Whois”查詢?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
如何使用PowerShell取得的公用IP位址(地理位置)的詳細信息?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
如何使用PowerShell檢查端口是否開放/關閉?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
如何使用PowerShell執行“tracert”?
Test-NetConnection www.google.com -TraceRoute
如何使用PowerShell修復家庭網絡的連接配置?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
如何使用PowerShell顯示TCP端口的連接?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
如何使用PowerShell縮短一個長的URL到一個短的URL?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
如何使用PowerShell取得代理伺服器的設置?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
如何使用PowerShell檢查本地電腦的DNS緩存?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
如何使用PowerShell清除本地電腦的DNS緩存?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
如何使用PowerShell清除遠程電腦的DNS緩存?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
如何使用PowerShell閱讀主機的文件?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
如何使用PowerShell產生一個隨機的密碼?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
如何使用PowerShell在遠程服務器上改變本地系統管理員的密碼?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
如何使用PowerShell尋找活動目錄(Active Directory)帳戶的密碼過期日期?
1 2 3 4 5 6 7 8 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed').'msDS-UserPasswordExpiryTimeComputed') # Solution 2 Get-Date -Date ((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
如何使用PowerShell列出特定服務器的所有打印機?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
如何使用PowerShell列出特定服務器的所有端口?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
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() |
如何使用PowerShell清除打印機(取消所有作業)?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
如何使用PowerShell打印打印機的測試頁?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
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
如何使用PowerShell列出註冊表配置單元?
Get-ChildItem -Path Registry::
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) } } } |
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:\' |
如何使用PowerShell以遞歸方式列出註冊表的項和子項?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
如何使用PowerShell尋找特定名稱的子項?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
如何使用PowerShell只返回註冊表子項的名稱?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
如何使用PowerShell列出的註冊表的值?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
如何使用PowerShell閱讀特定註冊表的值?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
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
如何使用PowerShell建立一個新的註冊表項?
New-Item -Path 'HKCU:\Software\MyApplication'
如何使用PowerShell建立註冊表的值?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
如何使用PowerShell修改現有的註冊表值?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
如何使用PowerShell刪除註冊表的值?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
如何使用PowerShell刪除註冊表項?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
如何使用PowerShell測試一個註冊表項是否存在?
Test-Path -Path 'HKCU:\Software\MyApplication'
如何使用PowerShell測試一個註冊表值是否存在?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
如何使用PowerShell刪除字符串開始的空白字符?
$string = ' PowershellGuru'
$string = $string.TrimStart()
如何使用PowerShell刪除字符串末尾的空白字符?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
如何使用PowerShell刪除字符串(開始和末尾)的空白字符?
$string = ' PowershellGuru '
$string = $string.Trim()
如何使用PowerShell將字符串轉換為大寫?
$string = 'powershellguru'
$string = $string.ToUpper()
如何使用PowerShell將字符串轉換為小寫?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
如何使用PowerShell選擇字符串“PowerShellGuru”中的子串“PowerShell”?
$string.Substring(0,10)
如何使用PowerShell選擇字符串“PowerShellGuru”中的子串 “Guru”?
$string.Substring(10)
如何使用PowerShell選擇“PowerShell123Guru”中的數字“123”?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
如何使用PowerShell取得字符串“PowerShellGuru”從零開始的索引的“Guru”?
$string.IndexOf('Guru') # 10
如何使用PowerShell檢查字符串是否為零值或空?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
如何使用PowerShell檢查字符串是否為零值、空、或只包含空白字符?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
如何使用PowerShell檢查字符串是否包含某個特定字母?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
如何使用PowerShell取得字符串的長度?
$string.Length
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
如何使用PowerShell匹配字符串中的一個或多個括號“[]”?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
如何使用PowerShell匹配字符串中的一個或多個括號“()”?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
如何使用PowerShell匹配字符串中的一個或多個括號大括號“{}”?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
如何使用PowerShell匹配字符串中的一個或多個括號大括號“<>”?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
如何使用PowerShell匹配字符串的任何小寫字母(abc)?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
如何使用PowerShell匹配字符串的任何大寫字母(ABC)?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
如何使用PowerShell匹配字符串的“[p”(p小寫)?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
如何使用PowerShell匹配字符串的“[P”(P大寫)?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
如何使用PowerShell以一行取代另一行?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
如何使用PowerShell將字符串的除法運算轉換為(百分比)?
(1/2).ToString('P')
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
如何使用PowerShell選擇句子的最後一個字?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
如何使用PowerShell取得一個句子最長的單詞?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
如何使用PowerShell計算句子中某個字符串出現的次數?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
如何使用PowerShell將字符串的每一個字符複製至字符數組?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
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 |
如何使用PowerShell將字符串編碼和解碼成為Base64?
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 |
如何使用PowerShell將數字轉換成為二進制/將二進制轉換成為數字?
1 2 3 4 5 |
# Base 10 to Base 2 [System.Convert]::ToString(255,2) # Base 2 to Base 10 [System.Convert]::ToInt32('11111111',2) |
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
如何使用PowerShell列出System.Math class 的方法?
[System.Math] | Get-Member -Static -MemberType Method
如何使用PowerShell返回絕對值?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
如何使用PowerShell返回指定數字的正弦角度?
[Math]::ASin(1) #Returns 1,5707963267949
如何使用PowerShell返回上限值?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
如何使用PowerShell返回下限值?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
如何使用PowerShell返回指定數字的自然對數(base e)?
[Math]::Log(4) #Returns 1,38629436111989
如何使用PowerShell返回指定數字的函數 (base 10)?
[Math]::Log10(4) #Returns 0,602059991327962
如何使用PowerShell返回兩個數值的最大值?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
如何使用PowerShell返回兩個數值的最小值?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
如何使用PowerShell返回數字的指定的指數?
[Math]::Pow(2,4) #Returns 16
如何使用PowerShell將一個小數值返回最接近的整數值?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
如何使用PowerShell將一個整數值返回小數值?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
如何使用PowerShell將指定數目返回平方根?
[Math]::Sqrt(16) #Returns 4
如何使用PowerShell返回PI常數?
[Math]::Pi #Returns 3,14159265358979
如何使用PowerShell返回自然對數底(常數e)?
[Math]::E #Returns 2,71828182845905
如何使用PowerShell檢查一個數字是否偶數或奇數?
[bool]($number%2)
Hashtables
如何使用PowerShell建立一個空的散列表(hashtable)?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
如何使用PowerShell建立散列表(hashtable)的項目?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
如何使用PowerShell建立一個項目以序/名稱(有序字典)排序的散列表(hashtable)的?
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
如何使用PowerShell添加項目(key-value pair 鍵值對)至散列表(hashtable)?
$hashtable.Add('Key4', 'Value4')
如何使用PowerShell取得散列表(hashtable)的特定值?
1 2 3 4 5 6 7 |
# Returns only Value $hashtable.Key1 $hashtable['Key1'] $hashtable.Item('Key1') # Returns Key and Value $hashtable.GetEnumerator() | Where-Object{$_.Name -eq 'Key1'} |
如何使用PowerShell取得散列表(hashtable)的最小值?
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 |
如何使用PowerShell取得散列表(hashtable)的最大值?
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 |
如何使用PowerShell修改散列表(hashtable)的項目?
$hashtable.Set_Item('Key1', 'Value1Updated')
如何使用PowerShell刪除散列表(hashtable)的項目?
$hashtable.Remove('Key1')
如何使用PowerShell清除散列表(hashtable)?
$hashtable.Clear()
如何使用PowerShell檢查散列表(hashtable)特定鍵/值的存在?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
如何使用PowerShell以鍵/值在散列表(hashtable)進行排序?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
如何使用PowerShell建立一個空的數組?
$array = @()
$array = [System.Collections.ArrayList]@()
如何使用PowerShell建立數組的項目?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
如何使用PowerShell添加項目到數組?
$array += 'D'
[void]$array.Add('D')
如何使用PowerShell修改數組的項目?
$array[0] = 'Z' # 1st item[0]
如何使用PowerShell檢查數組的大小?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
如何使用PowerShell檢索數組的中一個/多個/所有項目?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
如何使用PowerShell刪除數組的空項目?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
如何使用PowerShell檢查某個項目是否存在數組裡?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
如何使用PowerShell尋找數組一個項目的索引號?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
如何使用PowerShell相反數組項目的順序?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
如何使用PowerShell在數組中產生隨機項目?
$array | Get-Random
如何使用PowerShell按升序/降序方式排序數組?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
如何使用PowerShell計算數組的項目數目?
$array.Count
如何使用PowerShell添加數組到另一個數組?
$array1 = 'A', 'B', 'C'