Концепция : Наиболее часто задаваемые вопросы по PowerShell.
Вы можете использовать этот список для того, чтобы :
- Скопировать/вставить команды в скрипт
- Ознакомиться с синтаксисом определённой команды
- Улучшить свои технические знания
- Узнать о новых командах
- Подготовиться к собеседованию
Обновлено |
07 октября 2015
|
Автор | powershell-guru.com |
Источник | russian.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 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Check if a profile exists Test-Path -Path $PROFILE # Current User,Current Host Test-Path -Path $PROFILE.CurrentUserCurrentHost # Current User,Current Host Test-Path -Path $PROFILE.CurrentUserAllHosts # Current User,All Hosts Test-Path -Path $PROFILE.AllUsersCurrentHost # All Users, Current Host Test-Path -Path $PROFILE.AllUsersAllHosts # All Users, All Hosts # Create a new profile for current user New-Item -ItemType File -Force $PROFILE # CurrentUserCurrentHost New-Item -ItemType File -Force $PROFILE.CurrentUserCurrentHost New-Item -ItemType File -Force $PROFILE.CurrentUserAllHosts # Edit psEdit $PROFILE (only for ISE) ise $PROFILE (only for ISE) notepad.exe $PROFILE # Reload (without restarting Powershell) & $PROFILE .$PROFILE # List profiles $PROFILE | Format-List * -Force |
Как установить паузу на 5 секунд/минут в скрипте с помощью PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Как узнать время последней загрузки с помощью PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Как получить ускорители типов с помощью PowerShell?
1 |
[PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::Get.GetEnumerator() | Select-Object -Property @{Name='Key'; Expression={$_.Key}},@{name='Value'; Expression={$_.Value}} | Sort-Object -Property Key | Format-Table -AutoSize |
Как вывести список программ автозагрузки с помощью PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Как удалить приложение с помощью PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Как сделать скриншот рабочего стола или активного окна с помощью PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Как узнать количество сообщений для очередей MSMQ с помощью PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Как установить исполнительную политику с помощью PowerShell?
1 2 3 4 5 6 7 8 9 10 11 |
# Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode. Set-ExecutionPolicy -ExecutionPolicy Restricted # AllSigned - Only scripts signed by a trusted publisher can be run. Set-ExecutionPolicy -ExecutionPolicy AllSigned # RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run. Set-ExecutionPolicy -ExecutionPolicy RemoteSigned # Unrestricted - No restrictions - All Windows PowerShell scripts can be run. Set-ExecutionPolicy -ExecutionPolicy Unrestricted |
Как создать ярлык с помощью PowerShell?
1 2 3 4 |
$shell = New-Object -ComObject WScript.Shell $shortcut = $shell.Createshortcut("$HOME\Desktop\Procexp.lnk") $shortcut.TargetPath = 'C:\SysinternalsSuite\procexp.exe' $shortcut.Save() |
Как прикрепить или открепить программу в панели задач с помощью PowerShell?
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
Как открыть Windows Explorer с помощью PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Как вывести список драйверов устройств с помощью PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Как создать GUID с помощью PowerShell?
1 2 3 4 5 6 7 8 9 10 11 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($_)" } |
Как cмонтировать 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 |
Как проверить, установлена ли версия 4.5 .NET Framework, с помощью 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 MB) на диске D: с помощью PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Как удалить файл подкачки на диске С: с помощью 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
Как запаковать/zip файлы с помощью 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 |
Как распаковать/unzip файлы с помощью 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)
Как отобразить размер файла в КБ с помощью 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 |
Как проверить, имеет ли файл расширение, с помощью 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
Как проверить, существует ли файл, с помощью 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 *).Name # Solution 2 (Get-ADGroupMember 'Domain Controllers').Name # Solution 3 ((Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))')).Name # Solution 4 ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).DomainControllers.Name |
Как найти неудачные 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').DistinguishedName (Get-ADGroupMember 'Powershell Guru').Samaccountname # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
Как узнать участников группы (в т.ч. и рекурсивных) в Active Directory с помощью PowerShell?
1 2 |
(Get-ADGroupMember 'Powershell Guru' -Recursive).DistinguishedName (Get-ADGroupMember 'Powershell Guru' -Recursive).Samaccountname |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | Select-Object -ExpandProperty Samaccountname).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | Select-Object -ExpandProperty Samaccountname).Count |
Users
Как использовать маски в фильтре “Get-ADUser” в Active Directory с помощью PowerShell?
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
Как переместить пользователя в другую OU в Active Directory с помощью PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Как найти весь MemberOf (включая вложения) для пользователя с помощью PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Как получить MemberOf (кратко/усеченно) для пользователя с помощью PowerShell?
(Get-ADUser -Identity $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 и (Tele)phone 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
Как сбросить пароль для одной учётной записи пользователя в 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 (Organizational Unit) для пользователя в Active Directory с помощью PowerShell?
[regex]::match("$((Get-ADUser -Identity $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 -Identity $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 -Identity $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
1 2 |
$dn = (Get-ADUser -Identity $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
Как посмотреть владельца учётной записи в Active Directory с помощью PowerShell?
1 2 |
$dn = (Get-ADUser -Identity $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 -Identity $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-адрес (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
Как извлечь дату (10/02/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
Как извлечь “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()
Как узнать количество оперативной памяти компьютера с помощью 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 [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
Как закодировать и декодировать URL (в формате ASCII) с помощью 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 |
Как узнать, кому принадлежит сайт, с помощью 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"
Как узнать настройки прокси-сервера с помощью 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 -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
Как посмотреть список принтеров для конкретного сервера с помощью PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Как перечислить все порты для конкретного сервера с помощью PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Как изменить комментарий/расположение принтера с помощью 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)
Как узнать, является ли строка пустой, либо состоящей лишь из пробелов, с помощью 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
Как проверить наличие одной или нескольких скобок “< >” в строке с помощью 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
Как проверить наличие “[p” (p строчная) в строке с помощью PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Как проверить наличие “[P” (P прописная) в строке с помощью PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Как заменить одну строку другой с помощью PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Как преобразовать операцию деления в строку (в процентах) с помощью PowerShell?
(1/2).ToString('P')
Как сортировать строки, содержащие цифры, с помощью PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Как выбрать последнее слово в предложении с помощью PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Как выбрать самое длинное слово в предложении с помощью PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Как подсчитать, сколько раз строка встречается в предложении, с помощью Powershell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Как скопировать каждый символ в строке в массив символов с помощью PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Как преобразовать первую букву строки в прописную с помощью PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Как добавить в строку (слева или справа) с помощью Powershell?
1 2 3 4 5 6 7 |
# With whitespaces $padRight = 'test'.PadRight(25) $padLeft = 'test'.PadLeft(25) # With characters $padRight = 'test'.PadRight(25,'.') # Return test.................... $padLeft = 'test'.PadLeft(25,'.') # Return ....................test |
Как закодировать и декодировать строку в Base64 с помощью Powershell?
1 2 3 4 5 6 7 8 9 10 |
# Encode $string = [System.Text.Encoding]::UTF8.GetBytes('test') $encoded = [System.Convert]::ToBase64String($string) # Decode $string = [System.Convert]::FromBase64String($encoded) $decoded = [System.Text.Encoding]::UTF8.GetString($string) # Encoded : c3RldmU= # Decoded : test |
Как преобразовать число в двоичную систему исчисления и наоборот с помощью PowerShell?
1 2 3 4 5 |
# Base 10 to Base 2 [System.Convert]::ToString(255,2) # Base 2 to Base 10 [System.Convert]::ToInt32('11111111',2) |
Как вернуть имя только последней папки пути с помощью PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Как вернуть имя только последнего элемента пути с помощью PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Как перечислить методы класса System.Math с помощью PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
Как вернуть абсолютное значение с помощью PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Как вычислить угол, синус которого имеет определенное значение, с помощью PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
Как округлить число в большую сторону с помощью PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Как округлить число в меньшую сторону с помощью PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Как вычислить простой логарифм заданного числа (по основанию e), с помощью PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
Как вычислить десятичный логарифм заданного числа с помощью 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' } |
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')
Как получить конкретное значение из хэш-таблицы с помощью PowerShell?
1 2 3 4 5 6 7 |
# Returns only Value $hashtable.Key1 $hashtable['Key1'] $hashtable.Item('Key1') # Returns Key and Value $hashtable.GetEnumerator() | Where-Object{$_.Name -eq 'Key1'} |
Как получить минимальное значение из хэш-таблицы с помощью PowerShell?
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',