Концепция : Най-често задаваните въпроси за PowerShell.
Можете да използвате този списък по различни начини :
- За да копирате / поставяте команди в скрипт
- За да видите бързо синтаксиса на конкретна команда
- За да подобрите техническите си познания
- За да откриете нови команди
- За да се подготвите за интервю за работа
Обновено |
7 юли, 2015
|
Автор | powershell-guru.com |
Източник | bulgarian.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 10 |
# Create New-Item -Type file -Force $profile # Edit psEdit $profile ise $profile # Reload (without restarting Powershell) & $profile .$profile |
Как да направя пауза от 5 секунди / минути в скрипт с Powershell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Как да стигна до последния boot time с 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 12 13 14 15 16 17 18 19 |
# Empty GUID [GUID]::Empty 00000000-0000-0000-0000-000000000000 # New GUID (lower case by default) [GUID]::NewGuid() 7049b4a9-e4bc-4008-a683-067934bd39cf # New GUID (upper case) $guid = ([GUID]::NewGuid()).ToString().ToUpper() DD7F5A7B-F46B-49D0-B8A1-D8D1360D2E27 # New GUID with a specific value [GUID]('bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7') bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7 # New GUID (Powershell v5) New-Guid cdcaa4d9-c85f-40d7-afd9-32f003afa130 |
Как да стигнем до мястото на временната директория за текущия потребител с Powershell?
[System.IO.Path]::GetTempPath()
Как да се съедините директория и поддиректория в един единствен път с PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Как да се изброят всички кратки команди “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
Как да настроите Fullscreen прозорец с 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
Как да получите 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: drive с Powershell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Как да изтриете Pagefile на C: drive с 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?
1 2 3 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt' -Encoding ascii 'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt 'Line1', 'Line2', 'Line3' > file.txt |
Как да получите пълното име на текущия скриптов файл с Powershell?
$MyInvocation.MyCommand.Path
Как да декомпресирате / архивирани файлове с Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
### COMPRESS ONE FILE ### # Powershell v5 Compress-Archive -Path $fileSource -DestinationPath $fileDestination ### COMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::CreateFromDirectory($folderSource,$fileDestination) # Powershell v5 Compress-Archive -Path $folderSource -DestinationPath $fileDestination |
Как да декомпресирате / разархивирайте файлове с Powershell?
1 2 3 4 5 6 7 8 9 10 |
### UNCOMPRESS ONE FILE ### # Powershell v5 Expand-Archive -Path $fileSource -DestinationPath $folderDestination ### UNCOMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::ExtractToDirectory($fileSource, $folderDestination) |
Как да видите файловете в 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'
Как да bulk / batch преименувате множество файлове с 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?
1 2 3 4 5 6 7 8 9 10 |
(Get-ADDomainController).HostName # Solution 1 $env:LOGONSERVER # Solution 2 [System.Environment]::GetEnvironmentVariable('logonserver') # Solution 3 nltest.exe /dsgetdc:domain.com |
Как да намерите всички домейн контролери в домейн с 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
Как да намерите tombstone lifetime на гората в 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 |
Как да получите пътя на “Deleted Objects” в Active Directory с Powershell?
(Get-ADDomain).DeletedObjectsContainer
Как да включа AD Recycle Bin функцията в 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 Account от кошчето в 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'
Как да получите текущия logon сървър с 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} |
Как да се преброят членовете на група, с / без рекурсивни членове в 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
Как да използвате wildcard през филтъра на “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 |
Как да се промени описанието, офис и телефонния номер за потребителски акаунт в 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 |
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 (организационна единица) за потребител в 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
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'
Как да получите Organizational Unit (OU) майка на потребител с Active Directory с 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)
Как да се създаде организационна единица в Active Directory с Powershell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Как да получите подробности за организационна единица в Active Directory с Powershell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Как да променя описанието на организационна единица в 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 |
Как да добавя празни организационни единици с 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
Как да извлечете дата (2.10.2015) с 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
Как да направите колекция от паметта от garbage collector с 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 |
Как да конвертирате дата йъм 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) към дата (дата) с Powershell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Solution 1 $stringToDatetime = '07/15/2015' | Get-Date $stringToDatetime = '07-15-2015' | Get-Date # Solution 2 [Datetime]::ParseExact('07/15/2015', 'MM/dd/yyyy', $null) # Solution 3 $stringToDatetime = [Datetime]'7/15/2015' # Check $stringToDatetime Wednesday, July 15, 2015 12:00:00 AM $stringToDatetime.GetType().Name Datetime |
Как да се изчисли разликата (брой дни, часове, минути или секунди) между две дати с Powershell?
(New-TimeSpan -Start $dateStart -End $dateEnd).Days
(New-TimeSpan -Start $dateStart -End $dateEnd).Hours
(New-TimeSpan -Start $dateStart -End $dateEnd).Minutes
(New-TimeSpan -Start $dateStart -End $dateEnd).Seconds
Как да се сравнят две дати с Powershell?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False
Как да сортирате множество дати като за 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 } |
Как да откриете Hostname от IP адрес с Powershell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Как да намерите IP адреса, от Hostname с Powershell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Как да намерите FQDN от Hostname с Powershell?
[System.Net.Dns]::GetHostByName($computer).HostName
Как да намеря конфигурацията на мрежата (IP, Subnet, Gateway и 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 (геолокация) с 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 с Powershell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Как да получите настройките за Proxy с 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
Как да четем файла Hosts с 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() |
Как да направим purge (отмяна на всички работи) за принтер с 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
Как да покажа registry hives с 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
Как да получите на нулева база индексът на “Гуру” на низ “PowershellGuru” с Powershell?
$string.IndexOf('Guru') # 10
Как да се провери дали даден низ е NULL или празен с 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
Как да съответстват големи букви (ABC) в низ с Powershell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Как да съвпадат “[р” (стр малки букви) в низ с 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
Как да се върне ceiling с Powershell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Как да се върне floor с Powershell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Как да се върне естествения (base e) логаритъм на определено число с Powershell?
[Math]::Log(4) #Returns 1,38629436111989
Как да се върне base 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
Как да се върне естествената логаритмична база (constant 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 сортирана по ключ / име (ordered dictionary) с предмети с 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('Key4', 'Value4')
Как да получите конкретна стойност на Hashtable с Powershell?
1 2 3 4 5 6 |
# Returns only Value $hashtable.Key1 $hashtable.Get_Item('Key1') # Returns Key and Value $hashtable.GetEnumerator() | Where-Object{$_.Name -eq '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?