แนวคิด: คำถามที่ถามกันบ่อย ๆ เกี่ยวกับ Powershell
คุณสามารถใช้รายการในรูปแบบที่แตกต่างกันนี้:
- ในการคัดลอก / วางคำสั่งลงในสคริปต์
- ที่จะเห็นได้อย่างรวดเร็วถึงไวยากรณ์ของคำสั่งที่เฉพาะเจาะจง
- เพื่อพัฒนาความรู้ด้านเทคนิคของคุณ
- ที่จะค้นพบคำสั่งใหม่
- เพื่อเตรียมความพร้อมการสัมภาษณ์งาน
การปรับปรุง |
7 กรกฎาคม 2015
|
ผู้เขียน | powershell-guru.com |
แหล่ง | thai.powershell-guru.com |
หมวดหมู่ |
75
|
คำถามที่ |
610
|
System
วิธีการกำหนดว่าฉันจะเลือก Powershell รุ่นใดสำหรับฉัน?
1 2 3 4 5 6 7 8 9 |
# via Powershell $PSVersionTable.PSVersion.Major # via Registry (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine').PowerShellVersion # Versions 1 and 2 (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine').PowerShellVersion # Versions 3 and 4 # via Remote Invoke-Command -ComputerName $computer -ScriptBlock { $PSVersionTable.PSVersion.Major } |
วิธีการใช้ Powershell ในอีกรุ่นหนึ่งเพื่อจะได้มีความเข้ากันได้ย้อนหลัง?
powershell.exe -Version 2.0
วิธีการขอใช้ Powershell ในรุ่นต่ำสุด (3.0 และสูงกว่า) ในสคริปต์กับ PowerShell?
#Requires -Version 3.0
วิธีที่เรียกใช้สิทธิ์ของผู้ดูแลสำหรับสคริปต์กับ Powershell?
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()
วิธีการสร้างแก้ไขและโหลดรายละเอียดกับ Powershell?
1 2 3 4 5 6 7 8 9 |
# Create New-Item -Type file -Force $profile # Edit notepad.exe $profile # Reload (without restarting Powershell) & $profile .$profile |
วิธีการทำหยุด 5 วินาที / นาทีในสคริปต์กับ Powershell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
วิธีที่จะได้รับเวลาบูตที่ผ่านมากับ Powershell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
วิธีที่จะได้รับการเร่งชนิดต่าง ๆ ของ Powershell?
1 |
[PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get.GetEnumerator() | Select-Object -Property @{Name='Key'; Expression={$_.Key}},@{name='Value'; Expression={$_.Value}} | Sort-Object -Property Key | Format-Table -AutoSize |
วิธีการในรายการโปรแกรมเริ่มต้นด้วย Powershell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
วิธีการถอนการติดตั้งแอพลิเคชันที่มี Powershell?
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
วิธีการได้รับการนับข้อความสำหรับคิว MSMQ กับ Powershell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
วิธีการตั้งค่านโยบายการดำเนินการกับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 |
# Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode. Set-ExecutionPolicy -ExecutionPolicy Restricted # AllSigned - Only scripts signed by a trusted publisher can be run. Set-ExecutionPolicy -ExecutionPolicy AllSigned # RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run. Set-ExecutionPolicy -ExecutionPolicy RemoteSigned # Unrestricted - No restrictions - All Windows PowerShell scripts can be run. Set-ExecutionPolicy -ExecutionPolicy Unrestricted |
วิธีการสร้างทางลัดด้วย Powershell?
1 2 3 4 |
$shell = New-Object -ComObject WScript.Shell $shortcut = $shell.Createshortcut("$HOME\Desktop\Procexp.lnk") $shortcut.TargetPath = 'C:\SysinternalsSuite\procexp.exe' $shortcut.Save() |
วิธีการปักหรือเลิกตรึงโปรแกรมบนแถบงานกับ Powershell?
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
วิธีการเปิด Windows Explorer กับ 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
วิธีการสร้าง GUID กับ Powershell?
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') |
วิธีการรับตำแหน่งของไดเรกทอรีชั่วคราวสำหรับผู้ใช้ในปัจจุบันมี Powershell?
[System.IO.Path]::GetTempPath()
วิธีการเข้าร่วมเส้นทางและเส้นทางที่เด็กเข้ามาในเส้นทางเดียวกับ PowerShell?
Join-Path -Path C:\ -ChildPath \windows
วิธีการในรายการ cmdlets ทุกคน “Get- *” กับ Powershell?
Get-Command -Verb Get
วิธีการแสดงรายการโฟลเดอร์ระบบพิเศษกับ Powershell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
วิธีการติดตั้งไฟล์มาตรฐาน ISO / VHD กับ Powershell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
วิธีการตรวจสอบรุ่น NET Framework ที่ติดตั้งกับ Powershell?
1 |
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version -EA 0 | Where-Object -FilterScript { $_.PSChildName -match '^(?!S)\p{L}' } | Select-Object -Property PSChildName, Version |
วิธีการตรวจสอบว่า .NET Framework รุ่น 4.5 มีการติดตั้ง Powershell หรือเปล่า?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
วิธีการเริ่มต้นและหยุดหลักฐาน (การสร้างบันทึกของเซสชั่นของ Windows PowerShell) กับ 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
วิธีที่จะได้รับขนาด (กว้างและความสูง) ของภาพกับ Powershell?
1 2 3 4 5 6 7 |
$picture = New-Object -ComObject Wia.ImageFile $picture.LoadFile('C:\screenshot.jpg') [PSCustomObject] @{ Width = $picture.Width Height = $picture.Height } |
วิธีการได้รับผลิตภัณฑ์ที่ใช้ Windows กับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function Get-WindowsKey { ## function to retrieve the Windows Product Key from any PC ## by Jakob Bindslet (jakob@bindslet.dk) param ($targets = '.') $hklm = 2147483650 $regPath = 'Software\Microsoft\Windows NT\CurrentVersion' $regValue = 'DigitalProductId' Foreach ($target in $targets) { $productKey = $null $win32os = $null $wmi = [WMIClass]"\\$target\root\default:stdRegProv" $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue) $binArray = ($data.uValue)[52..66] $charsArray = 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9' ## decrypt base24 encoded binary data For ($i = 24; $i -ge 0; $i--) { $k = 0 For ($j = 14; $j -ge 0; $j--) { $k = $k * 256 -bxor $binArray[$j] $binArray[$j] = [math]::truncate($k / 24) $k = $k % 24 } $productKey = $charsArray[$k] + $productKey If (($i % 5 -eq 0) -and ($i -ne 0)) { $productKey = '-' + $productKey } } $win32os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $target $obj = New-Object -TypeName Object $obj | Add-Member -MemberType Noteproperty -Name Computer -Value $target $obj | Add-Member -MemberType Noteproperty -Name Caption -Value $win32os.Caption $obj | Add-Member -MemberType Noteproperty -Name CSDVersion -Value $win32os.CSDVersion $obj | Add-Member -MemberType Noteproperty -Name OSArch -Value $win32os.OSArchitecture $obj | Add-Member -MemberType Noteproperty -Name BuildNumber -Value $win32os.BuildNumber $obj | Add-Member -MemberType Noteproperty -Name RegisteredTo -Value $win32os.RegisteredUser $obj | Add-Member -MemberType Noteproperty -Name ProductID -Value $win32os.SerialNumber $obj | Add-Member -MemberType Noteproperty -Name ProductKey -Value $productKey $obj } } |
Perfmon
วิธีที่จะได้รับในปัจจุบัน “% เวลาประมวลผล” (โดยเฉลี่ย) ในช่วง 5 วินาที (10 ครั้ง) กับ Powershell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
วิธีการโหลดประกอบกับ Powershell?
1 2 3 4 5 6 |
Add-Type -AssemblyName 'System.Windows.Forms' Add-Type -Path 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll' # Deprecated [System.Reflection.Assembly]::LoadFrom('C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll') |
วิธีการตรวจสอบการประกอบ .NET ปัจจุบันเต็มไปด้วย Powershell?
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
วิธีการหา GAC (แคชสภาสากล) เส้นทางที่มี Powershell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
วิธีการคัดลอกผลไปยังคลิปบอร์ดกับ Powershell?
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
วิธีการได้รับข้อมูล Pagefile กับ Powershell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
วิธีที่จะได้รับขนาดที่แนะนำ (MB) สำหรับ Pagefile กับ Powershell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
วิธีการสร้าง Pagefile (4096 MB) ใน D: ไดรฟ์ที่มี Powershell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
วิธีการลบ Pagefile ใน C: ไดรฟ์ที่มี Powershell?
1 2 3 4 5 |
$privileges = Get-WmiObject -Class Win32_computersystem -EnableAllPrivileges $privileges.AutomaticManagedPagefile = $false $privileges.Put() $pagefile = Get-WmiObject -Query "select * from Win32_PageFileSetting where name='c:\\pagefile.sys'" $pagefile.Delete() # Reboot required |
Maintenance
วิธีการตรวจสอบการกระจายตัวของไดรฟ์ที่มี Powershell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
วิธีการตรวจสอบพื้นที่ว่างในดิสก์ไดรฟ์ที่มี Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Get-WmiObject -Class Win32_logicaldisk | Format-Table -Property @{ Name = 'Drive' Expression = {$_.DeviceID} }, @{ Name = 'Total size (GB)' Expression = {[decimal]('{0:N0}' -f($_.Size/1gb))} }, @{ Name = 'Free space(GB)' Expression = {[decimal]('{0:N0}'-f($_.Freespace/1gb))} }, @{ Name = 'Free (%)' Expression = {'{0,6:P0}' -f(($_.Freespace/1gb) / ($_.size/1gb))} } -AutoSize |
Files
วิธีการเปิดไฟล์ที่มี 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
วิธีการเขียนส่งออกไปยังไฟล์ที่มี Powershell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
วิธีที่จะได้รับชื่อเต็มของแฟ้มสคริปต์ปัจจุบันกับ Powershell?
$MyInvocation.MyCommand.Path
วิธีการบีบอัด / zip ไฟล์ที่มี Powershell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
วิธีการบีบอัดไฟล์ / เปิดเครื่องรูดกับ Powershell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
วิธีการดูไฟล์ในไฟล์ ZIP กับ Powershell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
วิธีการแสดงขนาดของไฟล์ใน KB กับ Powershell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
วิธีการหาไฟล์ขนาดใหญ่หรือน้อยกว่า 1 GB กับ Powershell?
1 2 3 4 5 |
# Larger than 1 GB Get-ChildItem -Path C:\ -Recurse -ErrorVariable $errorsSearch | Where-Object -FilterScript {$_.Length -gt 1GB} # Less than 1 GB Get-ChildItem -Path C:\ -Recurse -ErrorVariable $errorsSearch | Where-Object -FilterScript {$_.Length -lt 1GB} |
วิธีการแสดงชื่อของแฟ้มโดยไม่ต้องขยายกับ Powershell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
วิธีการแสดงนามสกุลของไฟล์ที่มี Powershell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
วิธีที่จะได้รับรุ่นของแฟ้มของแฟ้มที่มี Powershell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
วิธีที่จะได้รับกัญชาของไฟล์ Powershell?
(Get-FileHash $file).Hash
วิธีที่จะได้รับการตรวจสอบ MD5 / SHA1 ของไฟล์ที่มี Powershell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
วิธีการแสดงไฟล์ที่ซ่อนอยู่กับ Powershell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
วิธีการตรวจสอบหากไฟล์มีนามสกุลด้วย Powershell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
วิธีการตั้งค่าแฟ้มเป็นอ่านอย่างเดียวกับ Powershell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
วิธีการเปลี่ยนแอตทริบิวต์ LastWriteTime กับสัปดาห์ที่ผ่านสำหรับไฟล์ที่มี Powershell?
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'
วิธีการแสดง 10 สายล่าสุดของไฟล์ที่มี Powershell?
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
วิธีการตรวจสอบไฟล์ที่มีอยู่กับ Powershell?
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 |
วิธีการลบเส้นที่ซ้ำกันจากไฟล์ที่มี Powershell?
1 2 |
Get-Content -Path .\file.txt | Select-Object -Unique # Display Get-Content -Path .\file.txt | Select-Object -Unique | Set-Content -Path .\testing.txt # Save |
วิธีที่จะได้รับไฟล์ที่สร้างขึ้นไป / น้อยกว่า 1 เดือนในโฟลเดอร์ที่มี Powershell?
1 2 3 |
$1MonthAgo = (Get-Date).AddMonths(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
วิธีที่จะได้รับไฟล์ที่สร้างขึ้นไป / น้อยกว่า 1 ปีในโฟลเดอร์ที่มี Powershell?
1 2 3 |
$1YearAgo = (Get-Date).AddYears(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1YearAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1YearAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
วิธีการส่งออกค่าของตัวแปรที่จะไฟล์ที่มี Powershell?
Set-Content -Path file.txt -Value $variable
วิธีการนับจำนวนของไฟล์ (* .txt) ในโฟลเดอร์ที่มี Powershell?
1 2 3 |
[System.IO.Directory]::GetFiles('C:\scripts', '*.txt').Count (Get-ChildItem -Path 'C:\scripts' -Filter *.txt).Count (Get-ChildItem -Path 'C:\scripts' -Filter *.txt -Recurse).Count # Recursive |
วิธีการค้นหาสตริงภายในหลายไฟล์ด้วย PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
วิธีการแสดงครั้งแรก / บรรทัดสุดท้ายของไฟล์ที่มี PowerShell?
1 2 3 4 5 6 7 8 9 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt # First Line Get-Content -Path .\file.txt | Select-Object -First 1 # Returns Line1 (Get-Content -Path .\file.txt)[0] # Returns Line1 # Last Line Get-Content -Path .\file.txt | Select-Object -Last 1 # Returns Line3 (Get-Content -Path .\file.txt)[-1] # Returns Line3 |
วิธีการแสดงหมายเลขบรรทัดที่เฉพาะเจาะจงของไฟล์ที่มี PowerShell?
1 2 3 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt Get-Content -Path .\file.txt | Select-Object -Index 0 # Returns Line1 Get-Content -Path .\file.txt | Select-Object -Index 2 # Returns Line3 |
วิธีการนับจำนวนบรรทัดของไฟล์ที่มี PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
วิธีการนับจำนวนตัวอักษรและคำพูดของไฟล์ที่มี PowerShell?
1 2 3 4 5 6 7 8 9 10 |
'Test', 'Powershell', 'Test Powershell' | Out-File -FilePath file.txt # Words (Return 4) (Get-Content -Path .\file.txt | Measure-Object -Word).Words # Characters (Return 23) (Get-Content -Path .\file.txt | Measure-Object -Character).Characters # Characters and ignore whitespaces (Return 22) (Get-Content -Path .\file.txt | Measure-Object -Character -IgnoreWhiteSpace).Characters |
วิธีการดาวน์โหลดไฟล์ที่มี 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'
วิธีการคัดลอกไฟล์เดียวไปยังโฟลเดอร์หลายใน PowerShell?
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
วิธีการหาเซิร์ฟเวอร์แค็ตตาล็อกส่วนกลางใน Active Directory กับ Powershell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
วิธีการหาสถานที่ใน Active Directory กับ Powershell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
วิธีการหาตัวควบคุมโดเมนในปัจจุบันมี Powershell?
(Get-ADDomainController).HostName
วิธีการหาทุกตัวควบคุมโดเมนในโดเมนที่มี Powershell?
1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 Get-ADDomainController -Filter * | ForEach-Object -Process {$_.Name} # Solution 2 Get-ADGroupMember 'Domain Controllers' | ForEach-Object -Process {$_.Name} # Solution 3 Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))' | ForEach-Object -Process {$_.Name} # Solution 4 [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | ForEach-Object -Process {$_.DomainControllers} | ForEach-Object -Process {$_.Name} |
วิธีการค้นหาความล้มเหลวของการจำลองแบบ AD กับ Powershell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
วิธีการหาอายุการใช้งานหลุมฝังศพของป่าใน Active Directory กับ Powershell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
วิธีการได้รับรายละเอียดของป่า / โดเมนใน Active Directory กับ Powershell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
วิธีที่จะได้รับเส้นทางของ “วัตถุที่ถูกลบ” ภาชนะใน Active Directory กับ Powershell?
(Get-ADDomain).DeletedObjectsContainer
วิธีการเปิดใช้งานคุณลักษณะ AD ถังรีไซเคิลใน Active Directory กับ Powershell?
1 |
Enable-ADOptionalFeature -Identity 'CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=domain,DC=com' -Scope ForestOrConfigurationSet -Target 'domain.com' |
วิธีการเรียกคืนบัญชี AD จากถังรีไซเคิลใน Active Directory กับ Powershell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
วิธีการหาบทบาท FSMO กับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 Get-ADForest | Format-List -Property SchemaMaster, DomainNamingMaster Get-ADDomain | Format-List -Property PDCEmulator, RIDMaster, InfrastructureMaster # Solution 2 netdom query fsmo # Solution 3 [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().SchemaRoleOwner [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().NamingRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().InfrastructureRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().RidRoleOwner |
วิธีการเชื่อมต่อกับตัวควบคุมโดเมนที่เฉพาะเจาะจงกับ Powershell?
Get-ADUser -Identity $user -Server 'serverDC01'
วิธีที่จะได้รับการเข้าสู่ระบบเซิร์ฟเวอร์ในปัจจุบันมี Powershell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
วิธีการดำเนินการ “gpupdate” บนคอมพิวเตอร์ที่มี Powershell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
วิธีการสร้างกลุ่มใหม่ใน Active Directory กับ Powershell?
1 |
New-ADGroup -Name 'Powershell Guru' -SamAccountName powershellguru -GroupCategory Security -GroupScope Global -DisplayName 'Powershell Guru' -Path 'OU=MyOU,DC=domain,DC=com' -Description 'My account' |
วิธีการเอากลุ่มใน Active Directory กับ Powershell?
Remove-ADGroup -Identity 'PowershellGuru'
วิธีการเพิ่มผู้ใช้ไปยังกลุ่มใน Active Directory กับ Powershell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
วิธีการเอาผู้ใช้จากกลุ่มใน Active Directory กับ Powershell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
วิธีการหากลุ่มที่ว่างเปล่า (มีไม่มีสมาชิก) ใน Active Directory กับ Powershell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
วิธีการนับกลุ่มที่ว่างเปล่า (มีไม่มีสมาชิก) ใน Active Directory กับ Powershell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
วิธีการรับสมาชิกของกลุ่มใน Active Directory กับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Solution 1 Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname} # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
วิธีการรับสมาชิกของกลุ่มกับสมาชิก recursive ใน Active Directory กับ Powershell?
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
วิธีการนับจำนวนของสมาชิกในกลุ่มที่มี / ไม่มีสมาชิก recursive ใน Active Directory กับ Powershell?
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
วิธีการใช้ตัวแทนในตัวกรองของ “Get-ADUser” ใน Active Directory กับ Powershell?
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
วิธีการย้ายผู้ใช้ไปยังอีก OU ใน Active Directory กับ Powershell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
วิธีการหาทุก MemberOf (ซ้อน) สำหรับผู้ใช้ที่มี Powershell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
วิธีที่จะได้รับ MemberOf (ชื่อสั้น / ตัดทอน) สำหรับผู้ใช้ที่มี Powershell?
(Get-ADUser $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object
1 2 |
Set-ADUser $samAccountName -DisplayName 'DisplayName' -GivenName 'Test' -Surname 'Powershell' -DisplayName 'Test Powershell' Rename-ADObject $dn -NewName 'Test Powershell' #FullName |
วิธีการเปลี่ยนคำอธิบาย, สำนักงานและ (Tele) หมายเลขโทรศัพท์สำหรับบัญชีผู้ใช้ใน Active Directory กับ Powershell?
Set-ADUser $samAccountName -Description 'IT Consultant' -Office 'Building B' -OfficePhone '12345'
1 2 3 4 5 |
# 31/12/2015 Set-ADAccountExpiration $samAccountName -DateTime '01/01/2016' # Never Clear-ADAccountExpiration $samAccountName |
วิธีการปลดล็อคบัญชีผู้ใช้ใน Active Directory กับ Powershell?
Unlock-ADAccount $samAccountName
วิธีการเปิด / ปิดการใช้งานบัญชีผู้ใช้ใน Active Directory กับ Powershell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
วิธีการลบบัญชีผู้ใช้ใน Active Directory กับ Powershell?
Remove-ADUser $samAccountName
วิธีการตั้งค่ารหัสผ่านสำหรับบัญชีผู้ใช้คนหนึ่งใน Active Directory กับ Powershell?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
วิธีการตั้งค่ารหัสผ่านสำหรับบัญชีผู้ใช้หลายคน (กลุ่ม) ใน Active Directory กับ Powershell?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
วิธีการหาเจ้าของของไฟล์ใน Active Directory กับ Powershell?
1 2 3 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList (Get-Acl -Path 'userFile.txt').Owner $sid = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value Get-ADUser $sid |
วิธีการหา OU (Organizational Unit) สำหรับผู้ใช้ใน Active Directory กับ Powershell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
วิธีการหาบัญชีผู้ใช้คนพิการใน Active Directory กับ Powershell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
วิธีการหาบัญชีผู้ใช้ที่หมดอายุใน Active Directory กับ Powershell?
Search-ADAccount -AccountExpired
วิธีการหาบัญชีผู้ใช้ล็อคใน Active Directory กับ Powershell?
Search-ADAccount -LockedOut
วิธีการหา SID ของบัญชีผู้ใช้ใน Active Directory กับ Powershell?
(Get-ADUser $user -Properties SID).SID.Value
วิธีการแปลงชื่อผู้ที่จะ SID ใน Active Directory กับ Powershell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
วิธีการแปลง SID ถึงชื่อผู้ใช้ใน Active Directory กับ Powershell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
วิธีการแยกเฉพาะชื่อของบัญชีผู้ใช้กับ Active Directory กับ Powershell?
1 2 3 |
$dn = 'CN=Powershell Test,OU=TEST,DC=domain,DC=com' $dn.Split(',')[0] # Returns "CN=Powershell Test" $dn.Split(',')[0].Split('=')[1] # Returns "Powershell Test" |
วิธีการหาวันที่ของการสร้าง / การเปลี่ยนแปลงของบัญชีผู้ใช้กับ Active Directory กับ Powershell?
Get-ADUser -Identity $user -Properties whenChanged, whenCreated | Format-List -Property whenChanged, whenCreated
วิธีการแสดงคุณสมบัติตัวเลือกและบังคับสำหรับคลาส “ผู้ใช้” กับ Active Directory กับ Powershell?
1 2 3 |
$schema = [DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema() $schema.FindClass('user').mandatoryproperties | Format-Table $schema.FindClass('user').optionalproperties | Format-Table |
วิธีที่จะได้รับเส้นทาง LDAP สำหรับผู้ใช้กับ Active Directory กับ Powershell?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
วิธีการเปลี่ยน CN (Canonical ชื่อ) สำหรับผู้ใช้กับ Active Directory กับ Powershell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
วิธีที่จะได้รับหน่วยองค์กร (OU) แม่ของผู้ใช้กับ Active Directory กับ Powershell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
วิธีที่จะได้รับเจ้าของผู้ใช้ (ที่สร้างบัญชี) กับ Active Directory กับ Powershell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
วิธีการแปลงคุณลักษณะ pwdLastSet สำหรับผู้ใช้กับ Active Directory กับ Powershell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
วิธีการทดสอบช่องทางที่ปลอดภัยระหว่างคอมพิวเตอร์ท้องถิ่นและโดเมนกับ Powershell?
Test-ComputerSecureChannel
วิธีการซ่อมแซมช่องทางที่ปลอดภัยระหว่างคอมพิวเตอร์ท้องถิ่นและโดเมนกับ Powershell?
Test-ComputerSecureChannel -Repair
วิธีการปิดการใช้งานบัญชีผู้ใช้คอมพิวเตอร์ใน Active Directory กับ Powershell?
Disable-ADAccount $computer
วิธีการหาเครื่องคอมพิวเตอร์ที่มีระบบปฏิบัติการที่เฉพาะเจาะจงใน Active Directory กับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Get-ADComputer -Filter 'OperatingSystem -eq "CentOS"' Get-ADComputer -Filter 'OperatingSystem -eq "GNU/Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Mac OS X"' Get-ADComputer -Filter 'OperatingSystem -eq "OnTap"' Get-ADComputer -Filter 'OperatingSystem -eq "Red Hat Enterprise Linux Server"' Get-ADComputer -Filter 'OperatingSystem -eq "redhat-linux-gnu"' Get-ADComputer -Filter 'OperatingSystem -eq "Samba"' Get-ADComputer -Filter 'OperatingSystem -eq "Ubuntu"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows NT"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Server"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows XP Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2003"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Business"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Entreprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Ultimate"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server® 2008 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8.1 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 Standard"' |
Organizational Unit (OU)
วิธีการสร้างหน่วยองค์กร (OU) ใน Active Directory กับ Powershell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
วิธีที่จะได้รับหน่วยองค์กร (OU) รายละเอียดใน Active Directory กับ Powershell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
วิธีการเปลี่ยนรายละเอียดของหน่วยองค์กร (OU) ใน Active Directory กับ Powershell?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
วิธีการเปิด / ปิดการใช้งานหน่วยองค์กร (OU) จากอุบัติเหตุการลบใน Active Directory กับ Powershell?
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 |
วิธีการเปิดใช้ลบอุบัติเหตุสำหรับทุกหน่วยองค์กร (OU) ใน Active Directory กับ Powershell?
1 |
Get-ADOrganizationalUnit -Filter * -Property ProtectedFromAccidentalDeletion | Where-Object -FilterScript { $_.ProtectedFromAccidentalDeletion -eq $false } | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true |
วิธีการลบหน่วยองค์กร (OU) ป้องกันจากอุบัติเหตุการลบใน Active Directory กับ Powershell?
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 |
วิธีการในรายการหน่วยงานที่ว่างเปล่า (ภายใต้กฎระเบียบ) กับ Powershell?
1 2 3 4 5 |
# Solution 1 Get-ADOrganizationalUnit -Filter * -Property 'msDS-Approx-Immed-Subordinates' | Where-Object -FilterScript {$_.'msDS-Approx-Immed-Subordinates' -eq 0} # Solution 2 ([adsisearcher]'(objectclass=organizationalunit)').FindAll() | Where-Object -FilterScript { (([adsi]$_.Path).PSbase.Children | Measure-Object).Count -eq 0 } |
วิธีที่จะได้รับผู้จัดการของกลุ่มที่มี Powershell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
วิธีการเอาที่อยู่ IP v4 (80.80.228.8) กับ Regex กับ Powershell ออกมา?
$example = 'The IP address is 80.80.228.8'
$ip = [regex]::match($example,'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').value
วิธีการสกัดที่อยู่ MAC (C0-D9-62-39-61-2D) คั่นด้วย “-” กับ Regex กับ Powershell?
$example = 'The MAC address is C0-D9-62-39-61-2D'
$mac = [regex]::match($example,'([0-9A-F]{2}[-]){5}([0-9A-F]{2})').value
วิธีการสกัดที่อยู่ MAC (C0: D9: 62: 39: 61: 2D) ที่มีตัวคั่น “:” กับ Regex กับ Powershell?
$example = 'The MAC address is C0:D9:62:39:61:2D'
$mac = [regex]::match($example,'((\d|([a-f]|[A-F])){2}:){5}(\d|([a-f]|[A-F])){2}').value
วิธีการสกัดวันที่ (2015/10/02) กับ Regex กับ Powershell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
วิธีการสกัด URL (www.powershell-guru.com) กับ Regex กับ Powershell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
วิธีการสกัดอีเมล (user@domain.com) กับ Regex กับ Powershell?
$example = 'The email is user@domain.com'
$email = [regex]::match($example,'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b').value
วิธีการสกัด “กูรู” จากตัวอย่างสตริงกับ Regex กับ Powershell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
วิธีการสกัด “guru.com” จากตัวอย่างสตริงกับ Regex กับ Powershell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
วิธีการสกัด “powershell-guru.com” จากตัวอย่างสตริงกับ Regex กับ Powershell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
วิธีการสกัด “123” จากตัวอย่างสตริงกับ Regex กับ Powershell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
วิธีการสกัด “$” (เครื่องหมายดอลลาร์) จากตัวอย่างสตริงกับ Regex กับ Powershell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
วิธีการแทนที่ตัวอักษร (* .com) อีกด้วย (* .fr) ในสตริงที่มี Regex กับ Powershell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
วิธีการเลี่ยงสตริงที่มี Regex กับ Powershell?
[regex]::Escape('\\server\share')
Memory
วิธีการบังคับให้คอลเลกชันของหน่วยความจำโดยการเก็บขยะที่มี Powershell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
วิธีที่จะได้รับ RAM ขนาดของเครื่องคอมพิวเตอร์ที่มี Powershell?
1 2 3 4 5 6 7 8 |
# Solution 1 Get-CimInstance -ClassName 'cim_physicalmemory' | ForEach-Object -Process {$_.Capacity /1GB} # Solution 2 (Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory /1GB # Solution 3 (systeminfo.exe | Select-String -Pattern 'Total Physical Memory:').ToString().Split(':')[1].Trim() |
Date
วิธีที่จะได้รับวันที่ปัจจุบันกับ Powershell?
Get-Date
[Datetime]::Now
วิธีการแสดงวันที่ในรูปแบบที่แตกต่างกันกับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
### DATETIME ### Get-Date -Format D : Tuesday, June 30, 2015 Get-Date -Format f : Tuesday, June 30, 2015 3:22 PM Get-Date -Format F : Tuesday, June 30, 2015 3:22:58 PM Get-Date -Format g : 6/30/2015 3:23 PM Get-Date -Format G : 6/30/2015 3:23:30 PM Get-Date -DisplayHint Date : Tuesday, June 30, 2015 Get-Date -DisplayHint DateTime : Tuesday, June 30, 2015 3:31:21 PM ### DATE ### Get-Date -Format d : 6/30/2015 Get-Date -Format yyyyMMdd : 20150630 Get-Date -UFormat '%d%m%Y' : 30062015 Get-Date -UFormat '%m%d%Y' : 06302015 Get-Date -UFormat '%Y%m%d' : 20150630 Get-Date -UFormat '%d.%m.%Y' : 30.06.2015 Get-Date -UFormat '%m.%d.%Y' : 06.30.2015 Get-Date -UFormat '%Y.%m.%d' : 2015.06.30 Get-Date -UFormat '%d-%m-%Y' : 30-06-2015 Get-Date -UFormat '%m-%d-%Y' : 06-30-2015 Get-Date -UFormat '%Y-%m-%d' : 2015-06-30 Get-Date -UFormat '%d/%m/%Y' : 30/06/2015 Get-Date -UFormat '%m/%d/%Y' : 06/30/2015 Get-Date -UFormat '%Y/%m/%d' : 2015/06/30 ### HOUR ### Get-Date -Format t : 3:23 PM Get-Date -Format T : 3:23:30 PM Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 28 (Minute) Get-Date -Format ss : 30 (Seconds) Get-Date -DisplayHint Time : 3:23:30 PM ### DAY ### Get-Date -Format dddd : Tuesday Get-Date -Format ddd : Tue Get-Date -Format dd : 30 ### MONTH ### Get-Date -Format MMMM : June Get-Date -Format MMM : Jun Get-Date -Format MM : 06 ### YEAR ### Get-Date -Format yyyy : 2015 |
วิธีการแปลงวันที่ (Datetime) วันที่ (String) กับ 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 |
วิธีการแปลงวันที่ (String) จนถึงปัจจุบัน (Datetime) กับ 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 $stringToDatetime = [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
วิธีการจัดเรียงแถวของวันเป็น Datetime กับ Powershell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
วิธีการเริ่มต้นและหยุดจับเวลาด้วย Powershell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
วิธีที่จะได้รับวันที่ปัจจุบันของสัปดาห์กับ Powershell?
(Get-Date).DayOfWeek #Sunday
วิธีการได้รับวันของเมื่อวานนี้ที่มี Powershell?
(Get-Date).AddDays(-1)
วิธีที่จะได้รับจำนวนวันในเดือน (ในกุมภาพันธ์ 2015) โดยมี Powershell?
[DateTime]::DaysInMonth(2015, 2)
วิธีที่จะทราบว่าปีอธิกสุรทินกับ Powershell?
[DateTime]::IsLeapYear(2015)
วิธีการในรายการเขตเวลาที่มี Powershell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
วิธีการเข้ารหัส (เพื่อรูปแบบ ASCII) และถอดรหัส URL กับ Powershell?
1 2 3 4 5 6 7 8 9 |
# Encode $url = 'http://www.powershell-guru.com' $encoded = [System.Web.HttpUtility]::UrlEncode($url) # Decode $decoded = [System.Web.HttpUtility]::UrlDecode($encoded) # Encoded : http%3a%2f%2fwww.powershell-guru.com # Decoded : http://www.powershell-guru.com |
สิ่งที่เทียบเท่าของคำสั่งเครือข่ายพื้นเมืองที่มี Powershell คืออะไร?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# ipconfig Get-NetIPConfiguration Get-NetIPAddress # ping Test-NetConnection # tracert Test-NetConnection -TraceRoute # route Get-NetRoute # nslookup Resolve-DnsName # Windows 8.1 & Windows 2012 ([System.Net.Dns]::GetHostEntry($IP)).Hostname # IP > PC ([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString # PC > IP |
วิธีที่จะได้รับที่อยู่ IP กับ Powershell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
วิธีการปิดการใช้งานที่อยู่ IP v6 (IPv6) กับ Powershell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
วิธีการตรวจสอบที่อยู่ IP v4 (IPv4) ที่มี Powershell?
if([ipaddress]'10.0.0.1'){'validated'}
วิธีการหาที่อยู่ IP ภายนอกที่มี Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Solution 1 (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content (iwr -Uri 'myexternalip.com/raw').Content # Alias # Solution 2 $webClient = New-Object -TypeName System.Net.WebClient $webClient.DownloadString('http://myexternalip.com/raw') # Solution 3 while ($true) { Write-Output -InputObject "$(Get-Date) - $((Invoke-WebRequest -Uri 'http://myexternalip.com/raw' -Method Get).Content)" Start-Sleep -Seconds 300 } |
วิธีการหาชื่อโฮสต์จากที่อยู่ IP กับ Powershell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
วิธีการหาที่อยู่ IP จากชื่อโฮสต์ที่มี Powershell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
วิธีการหา FQDN จากชื่อโฮสต์ที่มี Powershell?
[System.Net.Dns]::GetHostByName($computer).HostName
วิธีการหาค่าเครือข่าย (IP, ซับเน็ตเกตเวย์และ DNS) กับ Powershell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
วิธีการหาที่อยู่ MAC กับ Powershell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
วิธีการ ping คอมพิวเตอร์ที่มี Powershell?
1 2 3 4 5 6 |
# Solution 1 Test-Connection -ComputerName $computer -Quiet # Returns True / False # Solution 2 $ping = New-Object -TypeName System.Net.Networkinformation.Ping $ping.Send($computer) |
วิธีการตรวจสอบเครื่องคอมพิวเตอร์ที่เชื่อมต่อกับอินเทอร์เน็ตด้วย Powershell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
วิธีการดำเนินการค้นหา whois สำหรับเว็บไซต์ที่มี PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
วิธีการรับรายละเอียดของไอพีสาธารณะ (Geolocation) กับ Powershell?
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
วิธีการดำเนินการกับ tracert Powershell?
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
วิธีการแสดงการเชื่อมต่อกับพอร์ต TCP Powershell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
วิธีที่จะลดลง URL ที่ยาวเป็น URL เล็ก ๆ กับ Powershell?
$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
วิธีการตรวจสอบแคช DNS บนคอมพิวเตอร์ที่มี Powershell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
วิธีการล้างแคช DNS บนคอมพิวเตอร์ท้องถิ่นที่มี Powershell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
วิธีการล้างแคช DNS บนรีโมทคอมพิวเตอร์ที่มี Powershell?
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()
วิธีการหาวันหมดอายุรหัสผ่านของบัญชีใน Active Directory กับ Powershell?
1 2 3 4 5 6 7 8 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed').'msDS-UserPasswordExpiryTimeComputed') # Solution 2 Get-Date -Date ((Get-ADUser $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
วิธีการในรายการเครื่องพิมพ์ทั้งหมดสำหรับเซิร์ฟเวอร์ที่เฉพาะเจาะจงกับ Powershell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
วิธีการในรายการพอร์ตทั้งหมดสำหรับเซิร์ฟเวอร์ที่เฉพาะเจาะจงกับ Powershell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
วิธีการเปลี่ยนความเห็น / สถานที่สำหรับเครื่องพิมพ์กับ Powershell?
1 2 3 4 |
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'" $printer.Location = 'Germany' $printer.Comment = 'Printer - Test' $printer.Put() |
วิธีการล้าง (ยกเลิกงานทั้งหมด) สำหรับเครื่องพิมพ์ที่มี 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()
วิธีที่จะได้รับการรอคิวการพิมพ์สำหรับเครื่องพิมพ์กับ Powershell?
1 2 3 4 |
Get-WmiObject -Class Win32_PerfFormattedData_Spooler_PrintQueue | Select-Object -Property Name, @{ Expression = {$_.jobs} Label = 'Current Jobs' } | Format-Table -AutoSize |
Regedit
Read
วิธีการในการทำรายการรีจิสทรีกับ Powershell?
Get-ChildItem -Path Registry::
วิธีที่จะได้รับค่ารีจิสทรีและประเภทค่ากับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function Get-RegistryValue { Param ( [Parameter(Mandatory = $true)] [string]$RegistryKey ) $key = Get-Item -Path "Registry::$RegistryKey" $key.GetValueNames() | Sort-Object | ForEach-Object -Process { $name = $_ $type = $key.GetValueKind($name) switch ($type) { 'String' {'REG_SZ'} 'Binary' {'REG_BINARY'} 'Dword' {'REG_DWORD'} 'Qword' {'REG_QWORD'} 'MultiString' {'REG_MULTI_SZ'} 'ExpandString'{'REG_EXPAND_SZ'} Default {$null} } [PSCustomObject]@{ Name = $name Type = $type Data = $key.GetValue($name) } } } |
วิธีการในรายการรีจิสทรีซับคีย์สำคัญกับ Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#HKEY_CLASSES_ROOT New-PSDrive -PSProvider Registry -Root HKEY_CLASSES_ROOT -Name HKCR Get-ChildItem -Path 'HKCR:\' #HKEY_CURRENT_USER Get-ChildItem -Path 'HKCU:\Software' Get-ChildItem -Path Registry::HKEY_CURRENT_USER #HKEY_LOCAL_MACHINE Get-ChildItem -Path 'HKLM:\SYSTEM' Get-ChildItem -Path Registry::HKEY_LOCAL_MACHINE #HKEY_USERS New-PSDrive -PSProvider Registry -Root HKEY_USERS -Name HKU Get-ChildItem -Path 'HKU:\' #HKEY_CURRENT_CONFIG New-PSDrive -PSProvider Registry -Root HKEY_CURRENT_CONFIG -Name HKCC Get-ChildItem -Path 'HKCC:\' |
วิธีการในรายการรีจิสทรีซับคีย์สำคัญในวิธี recursive กับ 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
วิธีการอ่านค่ารีจิสทรีเฉพาะเจาะจงเกี่ยวกับคอมพิวเตอร์ระยะไกลด้วย Powershell?
1 2 3 4 5 |
$hostname = $computer $openRegedit = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $hostname) $openKey = $openRegedit.OpenSubKey('SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion') $keyValue = $openKey.GetValue('ProductName') $keyValue |
Write
วิธีการสร้างคีย์รีจิสทรีใหม่ที่มี 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)
วิธีการเลือกย่อย “Guru” ของสตริง “PowershellGuru” กับ Powershell?
$string.Substring(10)
วิธีการเลือกหมายเลข “123” ของ “Powershell123Guru” กับ Powershell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
วิธีการได้รับดัชนี zero-based ของ “Guru” ของสตริง “PowershellGuru” กับ Powershell?
$string.IndexOf('Guru') # 10
วิธีการตรวจสอบว่าสตริงเป็นโมฆะหรือเปล่ากับ Powershell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
วิธีการตรวจสอบว่า null สตริงว่างเปล่าหรือประกอบด้วยเฉพาะของตัวอักษรสีขาวพื้นที่กับ Powershell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
วิธีการตรวจสอบว่าสตริงที่มีตัวอักษรที่เฉพาะเจาะจงกับ Powershell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
วิธีการคืนความยาวของสตริงกับ Powershell?
$string.Length
วิธีการเชื่อมสองสตริงกับ Powershell?
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
วิธีการจับคู่สำหรับหนึ่งหรือวงเล็บมุมหลาย “& lt; & gt;” ในสตริงกับ Powershell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
วิธีการจับคู่ตัวอักษรตัวเล็ก ๆ (ABC) ในสตริงกับ Powershell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
วิธีการจับคู่ upperletters ใด ๆ (เอบีซี) ในสตริงที่มี Powershell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
วิธีการจับคู่ “[p” (P กรณีที่ต่ำกว่า) ในสตริงที่มี Powershell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
วิธีการจับคู่ “[P” (P กรณีบน) ในสตริงที่มี Powershell?
$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')
วิธีการจัดเรียงสายที่มีตัวเลขกับ Powershell?
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 |
วิธีการแปลงตัวอักษรตัวแรกเป็นตัวพิมพ์ใหญ่ของสตริงกับ Powershell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
วิธีการเลื่อน (ซ้ายหรือขวา) สตริงที่มี Powershell?
1 2 3 4 5 6 7 |
# With whitespaces $padRight = 'test'.PadRight(25) $padLeft = 'test'.PadLeft(25) # With characters $padRight = 'test'.PadRight(25,'.') # Return test.................... $padLeft = 'test'.PadLeft(25,'.') # Return ....................test |
วิธีการเข้ารหัสและถอดรหัสสตริงเพื่อ Base64 กับ Powershell?
1 2 3 4 5 6 7 8 9 10 |
# Encode $string = [System.Text.Encoding]::UTF8.GetBytes('test') $encoded = [System.Convert]::ToBase64String($string) # Decode $string = [System.Convert]::FromBase64String($encoded) $decoded = [System.Text.Encoding]::UTF8.GetString($string) # Encoded : c3RldmU= # Decoded : test |
วิธีการแปลงตัวเลขไบนารีและจากไบนารีกับ 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) |
วิธีการกลับเฉพาะโฟลเดอร์หลักสุดท้ายในเส้นทางที่มี Powershell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
วิธีการกลับเฉพาะรายการสุดท้ายในเส้นทางที่มี Powershell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
วิธีการในรายการวิธีการเรียน System.Math กับ Powershell?
[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
วิธีการคืน (ฐาน e) ลอการิทึมปกติของจำนวนที่ระบุกับ Powershell?
[Math]::Log(4) #Returns 1,38629436111989
วิธีการคืน ฐาน10 ลอการิทึมของจำนวนที่ระบุกับ Powershell?
[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
วิธีการคืน PI อย่างต่อเนื่องกับ Powershell?
[Math]::Pi #Returns 3,14159265358979
วิธีการคืนฐานลอการิทึมธรรมชาติ (e คงที่เสมอ) กับ Powershell?
[Math]::E #Returns 2,71828182845905
วิธีการตรวจสอบว่าเป็นจำนวนที่เป็นคู่หรือคี่กับ Powershell?
[bool]($number%2)
Hashtables
วิธีการสร้าง hashtable ที่ว่างเปล่ากับ Powershell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
วิธีการสร้าง Hashtable กับรายการที่มี Powershell?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
วิธีการสร้าง Hashtable เรียงลำดับตามคีย์ / ชื่อ (พจนานุกรมสั่งซื้อ) โดยมีรายการที่มี Powershell?
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
วิธีการเพิ่มรายการ (key-value pair) เพื่อตารางแฮชกับ Powershell?
$hashtable.Add('Key3', 'Value3')
วิธีที่จะได้รับค่าเฉพาะของ Hashtable กับ Powershell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
วิธีการได้รับค่าต่ำสุดของ Hashtable กับ Powershell?
1 2 3 4 5 6 7 8 |
$hashtable = @{ 'Key1' = '1' 'Key2' = '2' 'Key3' = '3' } $hashtable.GetEnumerator() | Sort-Object -Property Value | Select-Object -First 1 $hashtable.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -Last 1 |
วิธีการได้รับค่าสูงสุดของ Hashtable กับ Powershell?
1 2 3 4 5 6 7 8 |
$hashtable = @{ 'Key1' = '1' 'Key2' = '2' 'Key3' = '3' } $hashtable.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -First 1 $hashtable.GetEnumerator() | Sort-Object -Property Value | Select-Object -Last 1 |
วิธีการปรับเปลี่ยนรายการใน Hashtable กับ Powershell?
$hashtable.Set_Item('Key1', 'Value1Updated')
วิธีการเอารายการใน Hashtable กับ Powershell?
$hashtable.Remove('Key1')
วิธีการล้าง Hashtable กับ Powershell?
$hashtable.Clear()
วิธีการตรวจสอบสถานะของเฉพาะคีย์ / ค่าใน Hashtable กับ Powershell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
วิธีการจัดเรียงโดยคีย์ / ค่าใน Hashtable กับ Powershell?
$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
วิธีการเพิ่มอาร์เรย์จะ antoher กับ Powershell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
วิธีการหาข้อมูลที่ซ้ำกันจากแถวกับ Powershell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
วิธีการลบข้อมูลที่ซ้ำกันจากแถวกับ Powershell?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique