Канцэпцыя : Пытанні аб Powershell, што задаваліся найбольш часта.
Вы можаце выкарыстоўваць гэты спіс па-рознаму :
- Каб скапіяваць/ўставіць каманды ў сцэнар
- Каб хутка убачыць сінтаксіс пэўнай каманды
- Каб палепшыць тэхнічныя пазнання
- Каб даведацць новыя каманды
- Для падрыхтоўкі да сумоўя
Абноўлены |
7 ліпеня 2015
|
Аўтар | powershell-guru.com |
Крыніца | belarusian.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 з 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
Як пералічыць ўсе командлеты “Get-*” з PowerShell?
Get-Command -Verb Get
Як пералічыць спецыяльныя сістэмныя тэчкі з PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Як мантаваць файлы VHD/ISO з 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
Як атрымаць актыўны “% Processor Time” (асераднёны) ў апошнія 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 (Global Assembly Cache) з 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
Як атрымаць інфармацыю аб файле падпампоўкі з PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Як атрымаць рэкамендуемы памер (МБ) файла падпампоўкі з дапамогай PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Як стварыць файл падпампоўкі (4096 МБ) на дыск (D 🙂 з PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Як выдаліць файл падпампоўкі з дыску (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)
Як распакаваць/unzip файлы з дапамогай 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)
Як адлюстраваць памер файла ў КБ з PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Як знайсці файлы больш або менш, чым 1 Гб, з дапамогай 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 |
Як праверыць, цi мае файл пашырэнне з PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Як усталяваць файл “толькі для чытання” з PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Як змяніць для файла атрыбут “Зменены” на тыднёвую даўнасць з дапамогай 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
Як праверыць iснаванне файла з 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' |
Як атрымаць членаў групы з рэкурсіўных членаў ў Active Directory з дапамогай PowerShell?
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
Як выкарыстоўваць маскі ў фільтры “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'
Як знайсці ўсіх укладзеных членаў для карыстальніка з PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Як атрымаць членаў (кароткае імя/усечанае) для карыстальніка з 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 |
Як змяніць Description, Office і Telephone number для ўліковага запісу карыстальніка ў 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
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
Як знайсці ўладальніка файла ў 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 |
Як падзяліць Distinguished Name ўліковага запісу карыстальніка ў 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
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 Name) для карыстальніка ў Active Directory з дапамогай PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Як канвертаваць атрыбут 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)
Як стварыць Organizational Unit (OU) ў Active Directory з дапамогай PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Як атрымаць дэталі Organizational Unit (OU) ў Active Directory з дапамогай PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Як змяніць апісанне Organizational Unit (OU) ў Active Directory з дапамогай PowerShell?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
1 2 3 4 5 |
# Protection ON Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $true # Protection OFF Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false |
1 |
Get-ADOrganizationalUnit -Filter * -Property ProtectedFromAccidentalDeletion | Where-Object -FilterScript { $_.ProtectedFromAccidentalDeletion -eq $false } | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true |
1 2 |
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false Remove-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' |
1 2 |
$parent = $dn.Split(',',2)[1] $parent = (Get-ADOrganizationalUnit $parent -Properties CanonicalName).CanonicalName |
Як пералічыць пустыя Organizational Unit (OU) з 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-адрас (с0-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-адрас (с0: 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/02/10) з дапамогай 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
Як атрымаць email (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
Як атрымаць “guru” з радка з дапамогай 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
Як знайсці поўнае даменнае імя з імя хаста з 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
Як праверыць сувязь з кампутарам з дапамогай 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')
Як атрымаць інфармацыю аб публічным IP (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:\' |
Як пералічыць падразделы ключоў рэестра рэкурсіўным чынам з 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
Як атрымаць індэкс “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) |
Як падбiраць пад пару адну або некалькі дужак “[ ]” ў радку з PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Як падбiраць пад пару адну або некалькі круглых дужак “( )” ў радку з PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Як падбiраць пад пару адну або некалькі фігурных дужак “{ }” ў радку з PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Як падбiраць пад пару адну або некалькі кутніх дужак “< >” ў радку з PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Як знайсці малыя літары (abc) ў радку з PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Як знайсці вялікія літары (ABC) ў радку з PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Як знайсці “[р” (р ў ніжнім рэгістры) ў радку з PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Як знайсці “[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
Як вярнуць натуральны (з падставай е) лагарыфм зададзенага ліку з 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
Як вярнуць натуральную лагарыфмічную базу (пастаяннае е) з PowerShell?
[Math]::E #Returns 2,71828182845905
Як праверыць, калі нумар цотны ці няцотны, з PowerShell?
[bool]($number%2)
Hashtables
Як стварыць пустую хэш-табліцу з PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Як стварыць хэш-табліцу з элементамі з PowerShell?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
Як стварыць хэш-табліцу, адсартаваную па ключу/імя (ўпарадкаваны слоўнік) з элементамі з PowerShell?
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
Як дадаць элементы (пары ключ-значэнне) ў хэш-табліцу з PowerShell?
$hashtable.Add('Key3', 'Value3')
Як атрымаць канкрэтнае значэнне хэш-табліцы з PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Як атрымаць мінімальнае значэнне хэш-табліцы з 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 |
Як атрымаць максімальнае значэнне хэш-табліцы з 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 |
Як змяніць элементы ў хэш-табліцы з PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Як выдаліць элементы ў хэш-табліцы з PowerShell?
$hashtable.Remove('Key1')
Як ачысціць хэш-табліцу з PowerShell?
$hashtable.Clear()
Як праверыць наяўнасць пэўнага ключа/значэння ў хэш-табліцы з PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Як сартаваць ключ/значэнне ў хэш-табліцу з 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
Як дадаць масіў ў іншы масіў з 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
$array # Returns A,B,C
Як стварыць масіў з элементамі, пачынаючы з прэфікса (“user01”, “user02”,… “user10”), з PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Як пералічыць ACL карыстальніка AD з PowerShell?
(Get-Acl -Path "AD:\$dn").Access
Як пералічыць ACL тэчкі з PowerShell?
(Get-Acl -Path C:\scripts).Access