Konsepsiya : Powershell haqqında ən çox verilən suallar.
Siz bu siyahıdan müxtəlif məqsədlər üçün istifadə edə bilərsiniz :
- Əmrləri skriptə kopyalamaq/yapışdırmaq üçün
- Tez bir şəkildə müəyyən əmrin sintaksisini görmək üçün
- Öz texniki biliklərinizi artırmaq üçün
- Yeni əmrləri kəşf etmək üçün
- İş müsahibəsini hazırlamaq üçün
Yeniləndi |
İyul 13, 2015
|
Müəllif | powershell-guru.com |
Mənbə | azerbaijani.powershell-guru.com |
Kateqoriyalar |
75
|
Suallar |
610
|
System
Mənim PowerShell versiyamı necə müəyyən etməli?
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-i geriyə uyğunluq üçün başqa versiyada necə işə salmalı?
powershell.exe -Version 2.0
PowerShell ilə skriptdə minimal PowerShell versiyasını (3.0 və yuxarı) necə tələb etməli?
#Requires -Version 3.0
PowerShell ilə skript üçün inzibati imtiyazları necə tələb etməli?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
PowerShell ilə skriptin parametrlərini necə yoxlamalı?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
PowerShell ilə cari istifadəçi üçün məlumatları necə əldə etməli?
[Security.Principal.WindowsIdentity]::GetCurrent()
PowerShell ilə profili necə yaratmalı, redaktə etməli və yenidən yükləməli?
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 |
PowerShell ilə skriptdə 5 saniyə/dəqiqə fasiləni necə etməli?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
PowerShell ilə sonuncu önyükləmə vaxtını necə əldə etməli?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
PowerShell ilə növ sürətləndiricilərini necə əldə etməli?
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 ilə başlanğıc proqramları necə sadalamalı?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
PowerShell ilə proqramı necə aradan qaldırmalı?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
PowerShell ilə bütün işçi masasının və ya aktiv pəncərənin skrinşotunu necə götürməli?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
PowerShell ilə MSMQ sıraları üçün mesaj sayını necə əldə etməli?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
PowerShell ilə icra siyasətini necə təyin etməli?
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 ilə yarlığı necə yaratmalı?
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 ilə proqramı tapşırıqlar panelinə necə bəndləməli və oradan düşürməli?
1 2 3 4 |
$shell = New-Object -ComObject shell.application $program = $shell.Namespace($env:windir).Parsename('notepad.exe') $program.Invokeverb('TaskbarPin') $program.Invokeverb('TaskbarUnpin') |
PowerShell ilə Windows Explorer-i necə açmalı?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
PowerShell ilə cihaz drayverlərini necə sadalamalı?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
PowerShell ilə GUID-i necə yaratmalı?
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 ilə cari istifadəçi üçün müvəqqəti kataloqun yerini necə əldə etməli?
[System.IO.Path]::GetTempPath()
PowerShell ilə yolu kiçik yolla vahid bir yola necə birləşdirməli?
Join-Path -Path C:\ -ChildPath \windows
PowerShell ilə bütün cmdlets “Get- *” əmrlərini necə sadalamalı?
Get-Command -Verb Get
PowerShell ilə xüsusi sistem qovluqlarını necə sadalamalı?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
PowerShell ilə ISO / VHD fayllarını necə montajlamalı?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
PowerShell ilə quraşdırılmış .NET Framework versiyalarını necə yoxlamalı?
1 |
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version -EA 0 | Where-Object -FilterScript { $_.PSChildName -match '^(?!S)\p{L}' } | Select-Object -Property PSChildName, Version |
PowerShell ilə .NET Framework 4.5 versiyasının quraşdırılıb-quraşdırılmadığını necə yoxlamalı?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
PowerShell ilə transkripti (Windows PowerShell sessiyasının qeydini yaratmaq üçün) necə başlatmalı və dayandırmalı?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
PowerShell ilə cari kataloqu müəyyən yerə necə dəyişməli?
Set-Location -Path 'C:\scripts'
PowerShell ilə ekranı necə təmizləməli?
Clear-Host
cls # Alias
PowerShell ilə ekran ölçülərini necə dəyişməli?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
PowerShell ilə “tam ekran” pəncərəsini necə qurmalı?
mode.com 300
PowerShell ilə şəklin ölçülərini (enini və hündürlüyünü) necə əldə etməli?
1 2 3 4 5 6 7 |
$picture = New-Object -ComObject Wia.ImageFile $picture.LoadFile('C:\screenshot.jpg') [PSCustomObject] @{ Width = $picture.Width Height = $picture.Height } |
PowerShell ilə Windows məhsul açarını necə əldə etməli?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
function Get-WindowsKey { ## function to retrieve the Windows Product Key from any PC ## by Jakob Bindslet (jakob@bindslet.dk) param ($targets = '.') $hklm = 2147483650 $regPath = 'Software\Microsoft\Windows NT\CurrentVersion' $regValue = 'DigitalProductId' Foreach ($target in $targets) { $productKey = $null $win32os = $null $wmi = [WMIClass]"\\$target\root\default:stdRegProv" $data = $wmi.GetBinaryValue($hklm,$regPath,$regValue) $binArray = ($data.uValue)[52..66] $charsArray = 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9' ## decrypt base24 encoded binary data For ($i = 24; $i -ge 0; $i--) { $k = 0 For ($j = 14; $j -ge 0; $j--) { $k = $k * 256 -bxor $binArray[$j] $binArray[$j] = [math]::truncate($k / 24) $k = $k % 24 } $productKey = $charsArray[$k] + $productKey If (($i % 5 -eq 0) -and ($i -ne 0)) { $productKey = '-' + $productKey } } $win32os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $target $obj = New-Object -TypeName Object $obj | Add-Member -MemberType Noteproperty -Name Computer -Value $target $obj | Add-Member -MemberType Noteproperty -Name Caption -Value $win32os.Caption $obj | Add-Member -MemberType Noteproperty -Name CSDVersion -Value $win32os.CSDVersion $obj | Add-Member -MemberType Noteproperty -Name OSArch -Value $win32os.OSArchitecture $obj | Add-Member -MemberType Noteproperty -Name BuildNumber -Value $win32os.BuildNumber $obj | Add-Member -MemberType Noteproperty -Name RegisteredTo -Value $win32os.RegisteredUser $obj | Add-Member -MemberType Noteproperty -Name ProductID -Value $win32os.SerialNumber $obj | Add-Member -MemberType Noteproperty -Name ProductKey -Value $productKey $obj } } |
Perfmon
PowerShell ilə son 5 saniyədə (10 dəfə) cari “% Prosessor Vaxtı”nı (orta) necə əldə etməli?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
PowerShell ilə qovşaqları necə yükləməli?
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') |
PowerShell ilə yüklənmiş cari .NET qovşaqlarını necə yoxlamalı?
1 2 3 4 5 |
# Check All [System.AppDomain]::CurrentDomain.GetAssemblies() # Check specific one [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object -FilterScript { $_.FullName -like '*forms*' } |
PowerShell ilə GAC (Qlobal Qovşaq Keşi) yolunu necə tapmalı?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
PowerShell ilə nəticələri mübadilə buferinə necə kopyalamalı?
1 |
Get-Process | clip.exe |
PowerShell ilə mübadilə buferinin məzmununu necə əldə etməli?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
PowerShell ilə quraşdırılmış hotfiksləri necə əldə etməli?
Get-HotFix -ComputerName $computer
PowerShell ilə müəyyən bir tarixdən əvvəl/sonra quraşdırılmış hotfiksləri necə əldə etməli?
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 ilə hotfiksin quraşdırılıb-quraşdırılmadığını necə yoxlamalı?
Get-HotFix -Id KB2965142
PowerShell ilə uzaq kompüterdə quraşdırılmış hotfiksləri necə əldə etməli?
Get-HotFix -ComputerName $computer
Pagefile
PowerShell ilə Peycfayl məlumatlarını necə əldə etməli?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
PowerShell ilə Peycfayl üçün məsləhət görülən ölçünü (MB) necə əldə etməli?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
PowerShell ilə (D:) diskində Peycfaylı (4096 MB) necə yaratmalı?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
PowerShell ilə (C:) diskində Peycfaylı necə silməli?
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 ilə diskin fraqmentasiyasını necə yoxlamalı?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
PowerShell ilə disklərin həcmini necə yoxlamalı?
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 ilə faylı necə açmalı?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
PowerShell ilə faylı necə oxumalı?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
PowerShell ilə fayla çıxışı necə yazmalı?
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 ilə cari skript faylının tam adını necə əldə etməli?
$MyInvocation.MyCommand.Path
PowerShell ilə faylları necə sıxmalı/zip etməli?
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 ilə sıxılmış/zip edilmiş faylları necə çıxarmalı?
1 2 3 4 5 6 7 8 9 10 |
### UNCOMPRESS ONE FILE ### # Powershell v5 Expand-Archive -Path $fileSource -DestinationPath $folderDestination ### UNCOMPRESS ONE FOLDER ### # Compress the folder 'R:\temp\zip\FolderToCompress' and created the file compressedFile.zip Add-Type -AssemblyName 'System.IO.Compression.Filesystem' [System.IO.Compression.ZipFile]::ExtractToDirectory($fileSource, $folderDestination) |
PowerShell ilə ZIP arxivindəki faylları necəgörməli?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
PowerShell ilə faylı KB ölçüsündə necə göstərməli?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
PowerShell ilə 1 GB-dan çox və ya az olan faylları necə tapmalı?
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 ilə faylın adını uzantısız necə göstərməli?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
PowerShell ilə faylın uzantısını necə göstərməli?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
PowerShell ilə faylın fayl versiyasını necə əldə etməli?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
PowerShell ilə faylın haşını necə əldə etməli?
(Get-FileHash $file).Hash
PowerShell ilə faylın MD5/SHA1 kontrol qiymətini necə əldə etməli?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
PowerShell ilə gizli faylları necə göstərməli?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
PowerShell ilə faylın uzantısının olub-olmadığını necə yoxlamalı?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
PowerShell ilə faylı “Yalnız Oxu” vəziyyətinə necə salmalı?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
PowerShell ilə fayl üçün “LastWriteTime” atributunu sonuncu həftəyə necə dəyişməli?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
PowerShell ilə yeni faylı necə yaratmalı?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
PowerShell ilə faylın adını necə dəyişməli?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
PowerShell ilə birdən çox faylın adını birdəfəyə necə dəyişməli?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
PowerShell ilə faylı necə silməli?
Remove-Item -Path 'C:\scripts\file.txt'
PowerShell ilə faylın son 10 xəttini necə göstərməli?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
PowerShell ilə qovluğun bir neçə faylını blokdan necə çıxarmalı?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
PowerShell ilə fayldan boş xətləri necə aradan qaldırmalı?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
PowerShell ilə faylın mövcud olub-olmadığını necə yoxlamalı?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
PowerShell ilə qovluqda ən yeni/köhnə yaradılmış faylı necə əldə etməli?
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 ilə fayldan cüt xətləri necə aradan qaldırmalı?
1 2 |
Get-Content -Path .\file.txt | Select-Object -Unique # Display Get-Content -Path .\file.txt | Select-Object -Unique | Set-Content -Path .\testing.txt # Save |
PowerShell ilə qovluqda 1 aydan çox və ya az yaradılmış faylları necə əldə etməli?
1 2 3 |
$1MonthAgo = (Get-Date).AddMonths(-1) Get-ChildItem | ?{$_.LastWriteTime -lt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # More Get-ChildItem | ?{$_.LastWriteTime -gt $1MonthAgo} | Select-Object LastWriteTime,Name,DirectoryName # Less |
PowerShell ilə qovluqda 1 ildən çox və ya az yaradılmış faylları necə əldə etməli?
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 ilə dəyişənin dəyərini fayla necə ixrac etməli?
Set-Content -Path file.txt -Value $variable
PowerShell ilə qovluqdakı (* .txt) fayllarının sayını necə hesablamalı?
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 ilə birdən çox faylda xətti necə axtarmalı?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
PowerShell ilə faylın birinci/sonuncu xəttini necə göstərməli?
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 ilə faylın müəyyən xətt nömrəsini necə göstərməli?
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 faylın xətlərinin sayını necə hesablamalı?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
PowerShell ilə faylın simvol və sözlərinin sayını necə hesablamalı?
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 ilə faylı necə yükləməli?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
PowerShell ilə faylın tam yolunu necə göstərməli?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
PowerShell ilə bir faylı qovluğa necə kopyalamalı?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
PowerShell ilə bir faylı birdən çox qovluğa necə kopyalamalı?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
PowerShell ilə birdən çox faylı bir qovluğa necə kopyalamalı?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
PowerShell ilə Qlobal Kataloq serverlərini Aktiv Kataloqda necə tapmalı?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
PowerShell ilə Aktiv Kataloqda saytları necə tapmalı?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
PowerShell ilə cari domen kontrollerini necə tapmalı?
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 ilə domendə bütün domen kontrollerlərini necə tapmalı?
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} |
PowerShell ilə AD replikasiya uğursuzluqlarını necə tapmalı?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
PowerShell ilə Aktiv Kataloqda meşə üçün başdaşının müddətini necə tapmalı?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
PowerShell ilə Aktiv Kataloqda meşənin/domenin ətraflı məlumatlarını necə əldə etməli?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
PowerShell ilə Aktiv Kataloqda “Silinmiş Obyektlər” konteynerinin yolunu necə əldə etməli?
(Get-ADDomain).DeletedObjectsContainer
PowerShell ilə Aktiv Kataloqda AD Səbət funksiyasını necə aktivləşdirməli?
1 |
Enable-ADOptionalFeature -Identity 'CN=Recycle Bin Feature,CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,DC=domain,DC=com' -Scope ForestOrConfigurationSet -Target 'domain.com' |
PowerShell ilə Aktiv Kataloqda AD Hesabını Səbətdən necə bərpa etməli?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
PowerShell ilə FSMO rollarını necə tapmalı?
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 ilə müəyyən domen kontrollerinə necə qoşulmalı?
Get-ADUser -Identity $user -Server 'serverDC01'
PowerShell ilə cari sistemə giriş serverini necə əldə etməli?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
PowerShell ilə kompüterdə “gpupdate” funksiyasını necə yerinə yetirməli?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
PowerShell ilə Aktiv Kataloqda yeni qrupu necə yaratmalı?
1 |
New-ADGroup -Name 'Powershell Guru' -SamAccountName powershellguru -GroupCategory Security -GroupScope Global -DisplayName 'Powershell Guru' -Path 'OU=MyOU,DC=domain,DC=com' -Description 'My account' |
PowerShell ilə Aktiv Kataloqda qrupu necə aradan qaldırmalı?
Remove-ADGroup -Identity 'PowershellGuru'
PowerShell ilə Aktiv Kataloqda qrupa istifadəçini necə əlavə etməli?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
PowerShell ilə Aktiv Kataloqda istifadəçini qrupdan necə çıxarmalı?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
PowerShell ilə Aktiv Kataloqda (heç bir üzvü olmayan) boş qrupları necə tapmalı?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
PowerShell ilə Aktiv Kataloqda (heç bir üzvü olmayan) boş qrupları necə saymalı?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
PowerShell ilə Aktiv Kataloqda qrup üzvlərini necə əldə etməli?
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' |
PowerShell ilə Aktiv Kataloqda rekursiv üzvlü qrupun üzvlərini necə əldə etməli?
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
PowerShell ilə Aktiv Kataloqda rekursiv üzvlü/üzvsüz qrupun üzvlərini necə saymalı?
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
PowerShell ilə Aktiv Kataloqda “Get-ADUser” filtrində jokerdən necə istifadə etməli?
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
PowerShell ilə Aktiv Kataloqda istifadəçini digər OU-ya necə keçirməli?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
PowerShell ilə istifadəçi üçün (Yuva salmış) bütün üzvləri necə tapmalı?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
PowerShell ilə istifadəçi (qısa ad/qısaldılmış) Üzvləri necə əldə etməli?
(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 |
PowerShell ilə Aktiv Kataloqda istifadəçi hesabı üçün Təsviri, Ofisi və Telefon nömrəsini necə dəyişməli?
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 |
PowerShell ilə Aktiv Kataloqda istifadəçi hesabını kiliddən necə açmalı?
Unlock-ADAccount $samAccountName
PowerShell ilə Aktiv Kataloqda istifadəçi hesabını necə aktiv/deaktiv etməli?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
PowerShell ilə Aktiv Kataloqda istifadəçi hesabını necə aradan qaldırmalı?
Remove-ADUser $samAccountName
PowerShell ilə Aktiv Kataloqda bir istifadəçi hesabı üçün parolu necə sıfırlamalı?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
PowerShell ilə Aktiv Kataloqda bir neçə istifadəçi hesabı (toplu) üçün parolu necə sıfırlamalı?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
PowerShell ilə Aktiv Kataloqda faylın sahibini necə tapmalı?
1 2 3 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList (Get-Acl -Path 'userFile.txt').Owner $sid = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value Get-ADUser $sid |
PowerShell ilə Aktiv Kataloqda istifadəçi üçün OU (TƏşkilati vahidi) necə tapmalı?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
PowerShell ilə Aktiv Kataloqda deaktiv olunmuş istifadəçi hesablarını necə tapmalı?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
PowerShell ilə Aktiv Kataloqda vaxtı bitmiş istifadəçi hesablarını necə tapmalı?
Search-ADAccount -AccountExpired
PowerShell ilə Aktiv Kataloqda kilidlənmiş istifadəçi hesablarını necə tapmalı?
Search-ADAccount -LockedOut
PowerShell ilə Aktiv Kataloqda istifadəçi hesabının SID-ni necə tapmalı?
(Get-ADUser $user -Properties SID).SID.Value
PowerShell ilə Aktiv Kataloqda istifadəçi adını SID-yə necə çevirməli?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
PowerShell ilə Aktiv Kataloqda SID-ni istifadəçi adına necə çevirməli?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
PowerShell ilə Aktiv Kataloqda istifadəçi hesabının Fərqləndirici adını necə ayırmalı?
1 2 3 |
$dn = 'CN=Powershell Test,OU=TEST,DC=domain,DC=com' $dn.Split(',')[0] # Returns "CN=Powershell Test" $dn.Split(',')[0].Split('=')[1] # Returns "Powershell Test" |
PowerShell ilə Aktiv Kataloqda istifadəçi hesabının yaranma/modifikasiya tarixini necə tapmalı?
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 |
PowerShell ilə Aktiv Kataloqda istifadəçi üçün LDAP yolunu necə əldə etməli?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
PowerShell ilə Aktiv Kataloqda istifadəçi üçün CN (Kanonik Adı) necə dəyişməli?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
PowerShell ilə Aktiv Kataloqda istifadəçi üçün Təşkilati Vahid (ou) mənbəyini necə əldə etməli?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
PowerShell ilə Aktiv Kataloqda istifadəçinin sahibini (hesabı yaradanı) necə əldə etməli?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
PowerShell ilə Aktiv Kataloqda istifadəçi üçün PwdLastSet atributunu necə çevirməli?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
PowerShell ilə yerli kompüterlə domen arasındakı təhlükəsiz kanalı necə yoxlamalı?
Test-ComputerSecureChannel
PowerShell ilə yerli kompüterlə domen arasındakı təhlükəsiz kanalı necə təmir etməli?
Test-ComputerSecureChannel -Repair
PowerShell ilə Aktiv Kataloqda kompüter hesabını necə deaktiv etməli?
Disable-ADAccount $computer
PowerShell ilə Aktiv Kataloqda müəyyən Əməliyyat Sistemlərinə malik kompüterləri necə tapmalı?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Get-ADComputer -Filter 'OperatingSystem -eq "CentOS"' Get-ADComputer -Filter 'OperatingSystem -eq "GNU/Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Mac OS X"' Get-ADComputer -Filter 'OperatingSystem -eq "OnTap"' Get-ADComputer -Filter 'OperatingSystem -eq "Red Hat Enterprise Linux Server"' Get-ADComputer -Filter 'OperatingSystem -eq "redhat-linux-gnu"' Get-ADComputer -Filter 'OperatingSystem -eq "Samba"' Get-ADComputer -Filter 'OperatingSystem -eq "Ubuntu"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows NT"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Server"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows XP Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2003"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Business"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Entreprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Ultimate"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server® 2008 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8.1 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 Standard"' |
Organizational Unit (OU)
PowerShell ilə Aktiv Kataloqda Təşkilati Vahidi (OU) necə yaratmalı?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
PowerShell ilə Aktiv Kataloqda Təşkilati Vahidin (OU) ətraflı məlumatlarını necə əldə etməli?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
PowerShell ilə Aktiv Kataloqda TƏşkilati Vahidin (OU) təsvirini necə dəyişməli?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
PowerShell ilə Aktiv Kataloqda Təşkilati Vahidi (OU) təsadüfi silinmədən necə aktiv/deaktiv etməli?
1 2 3 4 5 |
# Protection ON Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $true # Protection OFF Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -ProtectedFromAccidentalDeletion $false |
PowerShell ilə Aktiv Kataloqda bütün Təşkilati Vahidlər üçün təsadüfi silinməni necə aktiv etməli?
1 |
Get-ADOrganizationalUnit -Filter * -Property ProtectedFromAccidentalDeletion | Where-Object -FilterScript { $_.ProtectedFromAccidentalDeletion -eq $false } | Set-ADOrganizationalUnit -ProtectedFromAccidentalDeletion $true |
PowerShell ilə Aktiv Kataloqda təsadüfi silinmədən qorunmuş Təşkilati Vahidi (OU) necə silməli?
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 ilə boş Təşkilati Vahidləri (OUs) necə sadalamalı?
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 ilə qrupun menecerini necə əldə etməli?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
PowerShell ilə Regeksli IP ünvan v4 (80.80.228.8) necə çıxartmalı?
$example = 'The IP address is 80.80.228.8'
$ip = [regex]::match($example,'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').value
PowerShell ilə Regeksli “-” ayırıcılı MAC ünvanı (C0-D9-62-39-61-2D) necə çıxartmalı?
$example = 'The MAC address is C0-D9-62-39-61-2D'
$mac = [regex]::match($example,'([0-9A-F]{2}[-]){5}([0-9A-F]{2})').value
PowerShell ilə Regeksli “:” ayırıcılı MAC ünvanı (C0:D9:62:39:61:2D) necə çıxartmalı?
$example = 'The MAC address is C0:D9:62:39:61:2D'
$mac = [regex]::match($example,'((\d|([a-f]|[A-F])){2}:){5}(\d|([a-f]|[A-F])){2}').value
PowerShell ilə Regeksli tarixi (10/02/2015) necə çıxartmalı?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
PowerShell ilə Regeksli URL (www.powershell-guru.com) ünvanını necə çıxartmalı?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
PowerShell ilə Regeksli e-poçtu (user@domain.com) necə çıxartmalı?
$example = 'The email is user@domain.com'
$email = [regex]::match($example,'(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b').value
PowerShell ilə “guru”nu Regeksli nümunə xəttdən necə çıxartmalı?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
PowerShell ilə “guru.com”u Regeksli nümunə xəttdən necə çıxartmalı?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
PowerShell ilə “powershell-guru.com”u Regeksli nümunə xəttdən necə çıxartmalı?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
PowerShell ilə “123”ü Regeksli nümunə xəttdən necə çıxartmalı?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
PowerShell ilə “$” (dollar nişanını) Regeksli nümunə xəttdən necə çıxartmalı?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
PowerShell ilə (*.com) simvolunu digər (*.fr) simvolla Regeksli nümunə xətdində necə əvəz etməli?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
PowerShell ilə Regeksli xətdən necə yayınmalı?
[regex]::Escape('\\server\share')
Memory
PowerShell ilə yaddaşın zibil kollektoru tərəfindən yığılmasını necə məcbur etməli?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
PowerShell ilə kompüterin RAM ölçüsünü necə əldə etməli?
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 ilə cari tarixi necə əldə etməli?
Get-Date
[Datetime]::Now
PowerShell ilə tarixi müxtəlif formatlarda necə göstərməli?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
### DATETIME ### Get-Date -Format D : Tuesday, June 30, 2015 Get-Date -Format f : Tuesday, June 30, 2015 3:22 PM Get-Date -Format F : Tuesday, June 30, 2015 3:22:58 PM Get-Date -Format g : 6/30/2015 3:23 PM Get-Date -Format G : 6/30/2015 3:23:30 PM Get-Date -DisplayHint Date : Tuesday, June 30, 2015 Get-Date -DisplayHint DateTime : Tuesday, June 30, 2015 3:31:21 PM ### DATE ### Get-Date -Format d : 6/30/2015 Get-Date -Format yyyyMMdd : 20150630 Get-Date -UFormat '%d%m%Y' : 30062015 Get-Date -UFormat '%m%d%Y' : 06302015 Get-Date -UFormat '%Y%m%d' : 20150630 Get-Date -UFormat '%d.%m.%Y' : 30.06.2015 Get-Date -UFormat '%m.%d.%Y' : 06.30.2015 Get-Date -UFormat '%Y.%m.%d' : 2015.06.30 Get-Date -UFormat '%d-%m-%Y' : 30-06-2015 Get-Date -UFormat '%m-%d-%Y' : 06-30-2015 Get-Date -UFormat '%Y-%m-%d' : 2015-06-30 Get-Date -UFormat '%d/%m/%Y' : 30/06/2015 Get-Date -UFormat '%m/%d/%Y' : 06/30/2015 Get-Date -UFormat '%Y/%m/%d' : 2015/06/30 ### HOUR ### Get-Date -Format t : 3:23 PM Get-Date -Format T : 3:23:30 PM Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 28 (Minute) Get-Date -Format ss : 30 (Seconds) Get-Date -DisplayHint Time : 3:23:30 PM ### DAY ### Get-Date -Format dddd : Tuesday Get-Date -Format ddd : Tue Get-Date -Format dd : 30 ### MONTH ### Get-Date -Format MMMM : June Get-Date -Format MMM : Jun Get-Date -Format MM : 06 ### YEAR ### Get-Date -Format yyyy : 2015 |
PowerShell ilə tarixi (Datetime) tarixə (String) necə çevirməli?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Solution 1 $datetimeToString = '{0:MM/dd/yy}' -f (Get-Date '07/15/2015') # Solution 2 $datetimeToString = (Get-Date '07/15/2015').ToShortDateString() # Check $datetimeToString 07/15/15 $datetimeToString.GetType().Name String |
PowerShell ilə tarixi (Datetime) tarixə (String) necə çevirməli?
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 ilə iki tarix arasındakı fərqi (Günlərin, Saatların, Dəqiqələrin və ya Saniyələrin sayını) necə hesablamalı?
(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 ilə iki tarixi necə müqayisə etməli?
(Get-Date 2015-01-01) -lt (Get-Date 2015-01-30) # True
(Get-Date 2015-01-01) -gt (Get-Date 2015-01-30) # False
PowerShell ilə tarixlərin matrisini “Datetime” kimi necə düzməli?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
PowerShell ilə saniyəölçəni necə işə salmalı və dayandırmalı?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
PowerShell ilə həftənin cari gününü necə əldə etməli?
(Get-Date).DayOfWeek #Sunday
PowerShell ilə dünənki tarixi necə əldə etməli?
(Get-Date).AddDays(-1)
PowerShell ilə aydakı günlərin sayını (2015-ci ilin fevral ayında) necə əldə etməli?
[DateTime]::DaysInMonth(2015, 2)
PowerShell ilə uzun ili necə bilməli?
[DateTime]::IsLeapYear(2015)
PowerShell ilə vaxt zonalarını necə sadalamalı?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
PowerShell ilə URL-i necə şifrələməli (ASCII formatına) və şifrəsini açmalı?
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 ilə doğma şəbəkə əmrlərinin ekvivalentləri hansılardır?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# ipconfig Get-NetIPConfiguration Get-NetIPAddress # ping Test-NetConnection # tracert Test-NetConnection -TraceRoute # route Get-NetRoute # nslookup Resolve-DnsName # Windows 8.1 & Windows 2012 ([System.Net.Dns]::GetHostEntry($IP)).Hostname # IP > PC ([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString # PC > IP |
PowerShell ilə IP ünvanları necə əldə etməli?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
PowerShell ilə IP ünvan V6-nı (IPv6) necə deaktiv etməli?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
PowerShell ilə IP ünvan v4-ü (IPv4) necə təsdiqləməli?
if([ipaddress]'10.0.0.1'){'validated'}
PowerShell ilə xarici IP ünvanı necə tapmalı?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Solution 1 (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content (iwr -Uri 'myexternalip.com/raw').Content # Alias # Solution 2 $webClient = New-Object -TypeName System.Net.WebClient $webClient.DownloadString('http://myexternalip.com/raw') # Solution 3 while ($true) { Write-Output -InputObject "$(Get-Date) - $((Invoke-WebRequest -Uri 'http://myexternalip.com/raw' -Method Get).Content)" Start-Sleep -Seconds 300 } |
PowerShell ilə IP ünvandan Host adını necə tapmalı?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
PowerShell ilə Host adından IP ünvanı necə tapmalı?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
PowerShell ilə Host adından FQDN-i necə tapmalı?
[System.Net.Dns]::GetHostByName($computer).HostName
PowerShell ilə şəbəkə konfiqurasiyasını (Ip, Subnet, Gateway və DNS) necə tapmalı?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
PowerShell ilə MAC ünvanı necə tapmlı?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
PowerShell ilə kompüterlə əlaqəni necə yoxlamalı?
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 ilə kompüterin internetə qoşulub-qoşulmadığını necə yoxlamalı?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
PowerShell ilə sayt üçün “whois” axtarışını necə yerinə yetirməli?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
PowerShell ilə ictimai IP-nin (Geolokasiya) ətraflı məlumatlarını necə əldə etməli?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
PowerShell ilə portun açıq/bağlı olmasını necə yoxlamalı?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
PowerShell ilə “tracert”i necə yerinə yetirməli?
Test-NetConnection www.google.com -TraceRoute
PowerShell ilə ev şəbəkə əlaqəsi profilini necə düzəltməli?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
PowerShell ilə TCP port əlaqələrini necə göstərməli?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
PowerShell ilə uzun URL-i kiçik URL-ə necə çevirməli?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
PowerShell ilə proksi seçənəklərini necə əldə etməli?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
PowerShell ilə yerli kompüterdə DNS keşi necə yoxlamalı?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
PowerShell ilə yerli kompüterdə DNS keşi necə təmizləməli?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
PowerShell ilə uzaq kompüterlərdə DNS keşi necə təmizləməli?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
PowerShell ilə Hosts faylı necə oxumalı?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
PowerShell ilə təsadüfi parolu necə yaratmalı?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
PowerShell ilə uzaq serverdə administrator üçün yerli parolu necə dəyişməli?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
PowerShell ilə Aktiv Kataloqda hesabın parolunun bitmə tarixini necə tapmalı?
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 ilə müəyyən server üçün bütün printerləri necə sadalamalı?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
PowerShell ilə müəyyən server üçün bütün portları necə sadalamalı?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
PowerShell ilə printerin şərhini/yerini necə dəyişməli?
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 ilə printeri necə təmizləməli (bütün işləri ləğv etməli)?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
PowerShell ilə printer üçün sınaq səhifəsini necə çap etməli?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
PowerShell ilə printerlər üçün çap sıralarını necə əldə etməli?
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 ilə reyestr pətəklərinin necə sadalamalı?
Get-ChildItem -Path Registry::
PowerShell ilə reyestr dəyərlərini və dəyər növlərini necə əldə etməli?
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 ilə reyestr açarının alt açarlarını necə sadalamalı?
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 ilə reyestr açarının alt açarlarını rekursiv yolla necə sadalamalı?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
PowerShell ilə müəyyən adlı alt açarları necə tapmalı?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
PowerShell ilə reyestrin alt açarlarının yalnız adını necə qaytarmalı?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
PowerShell ilə reyestr dəyərlərini necə sadalamalı?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
PowerShell ilə müəyyən reyestr dəyərini necə oxumalı?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
PowerShell ilə uzaq kompüterdə müəyyən reyestr dəyərini necə oxumalı?
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 ilə yeni reyestr açarını necə yaratmalı?
New-Item -Path 'HKCU:\Software\MyApplication'
PowerShell ilə reyestr dəyərini necə yaratmalı?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
PowerShell ilə mövcud reyestr dəyərini necə dəyişməli?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
PowerShell ilə reyestr dəyərini necə silməli?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
PowerShell ilə reyestr açarını necə silməli?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
PowerShell ilə reyestr açarının mövcud olub-olmadığını necə yoxlamalı?
Test-Path -Path 'HKCU:\Software\MyApplication'
PowerShell ilə reyestr dəyərinin mövcud olub-olmadığını necə yoxlamalı?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
PowerShell ilə xəttin əvvəlindən məsafə simvollarını necə aradan qaldırmalı?
$string = ' PowershellGuru'
$string = $string.TrimStart()
PowerShell ilə xəttin sonundan məsafə simvollarını necə aradan qaldırmalı?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
PowerShell ilə xəttin (əvvəlindəki və sonundakı) məsafə simvollarını necə aradan qaldırmalı?
$string = ' PowershellGuru '
$string = $string.Trim()
PowerShell ilə xətti baş hərfə necə çevirməli?
$string = 'powershellguru'
$string = $string.ToUpper()
PowerShell ilə xətti kiçik hərfə necə çevirməli?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
PowerShell ilə “PowerShellGuru” xəttinin “PowerShell” alt xəttini necə seçməli?
$string.Substring(0,10)
PowerShell ilə “PowerShellGuru” xəttinin “Guru” alt xəttini necə seçməli?
$string.Substring(10)
PowerShell ilə “PowerShell123Guru”nun “123” rəqəmini necə seçməli?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
PowerShell ilə “PowerShellGuru” xəttindəki “Guru”nun sıfırdan başlayan indeksini necə əldə etməli?
$string.IndexOf('Guru') # 10
PowerShell ilə xəttin sıfır və ya boş olub-olmadığını necə yoxlamalı?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
PowerShell ilə xəttin sıfır, boş və ya yalnız məsafələrdən ibarət olub-olmadığını necə yoxlamalı?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
PowerShell ilə xətdə müəyyən hərfin olub-olmadığını necə yoxlamalı?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
PowerShell ilə xəttin uzunluğunu necə qaytarmalı?
$string.Length
PowerShell ilə iki xətti necə birləşdirməli?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
PowerShell ilə xətdə bir və ya bir neçə mötərizə “[]” üçün necə uyğunlaşmalı?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
PowerShell ilə xətdə bir və ya bir neçə girdə mötərizə “( )” üçün necə uyğunlaşmalı?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
PowerShell ilə xətdə bir və ya bir neçə qıvrım aşırma “{ }” üçün necə uyğunlaşmalı?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
PowerShell ilə xətdə bir və ya bir neçə bucaq mötərizələri “< >” üçün necə uyğunlaşmalı?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
PowerShell ilə xətdə hər hansı kiçik hərfləri (abc) necə uyğunlaşdırmalı?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
PowerShell ilə xətdə hər hansı baş hərfləri (ABC) necə uyğunlaşdırmalı?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
PowerShell ilə xətdə “[p” (p kiçik hərfi) necə uyğunlaşdırmalı?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
PowerShell ilə xətdə “[P” (P baş hərfi) necə uyğunlaşdırmalı?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
PowerShell ilə bir xətti digər xətlə necə əvəz etməli?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
PowerShell ilə bölgü əməliyyatını xəttə (faizə) necə çevirməli?
(1/2).ToString('P')
PowerShell ilə rəqəmlərdən ibarət xətləri necə sadalamalı?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
PowerShell ilə cümlənin sonuncu sözünü necə seçməli?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
PowerShell ilə cümlənin ən böyük sözünü necə əldə etməli?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
PowerShell ilə xəttin cümlə daxilində neçə dəfə olmasını necə saymalı?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
PowerShell ilə xətdəki hər simvolu simvol matrisinə necə kopyalamalı?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
PowerShell ilə ilk hərfi xəttin baş hərfinə necə çevirməli?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
PowerShell ilə xətti (sola və ya sağa) necə dartmalı?
1 2 3 4 5 6 7 |
# With whitespaces $padRight = 'test'.PadRight(25) $padLeft = 'test'.PadLeft(25) # With characters $padRight = 'test'.PadRight(25,'.') # Return test.................... $padLeft = 'test'.PadLeft(25,'.') # Return ....................test |
PowerShell ilə xətti Base64-ə necə şifrələməli və şifrədən açmalı?
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 ilə rəqəmi ikiliyə (və ya ikilikdən) necə çevirməli?
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 ilə yoldakı yalnız son ilkin qovluğu necə qaytarmalı?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
PowerShell ilə yoldakı yalnız son maddəni necə qaytarmalı?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
PowerShell ilə System.Math sinfinin üsullarını necə sadalamalı?
[System.Math] | Get-Member -Static -MemberType Method
PowerShell ilə mütləq dəyəri necə qaytarmalı?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
PowerShell ilə sinusu müəyyən rəqəm olan bucağı necə qaytarmalı?
[Math]::ASin(1) #Returns 1,5707963267949
PowerShell ilə tavan dəyərini necə qaytarmalı?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
PowerShell ilə döşəmə dəyərini necə qaytarmalı?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
PowerShell ilə müəyyən rəqəmin təbii (baza e) loqarifmini necə qaytarmalı?
[Math]::Log(4) #Returns 1,38629436111989
PowerShell ilə müəyyən rəqəmin baza 10 loqarifmini necə qaytarmalı?
[Math]::Log10(4) #Returns 0,602059991327962
PowerShell ilə iki dəyərin maksimumunu necə qaytarmalı?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
PowerShell ilə iki dəyərin minimumunu necə qaytarmalı?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
PowerShell ilə müəyyən gücə qaldırılmış rəqəmi necə qaytarmalı?
[Math]::Pow(2,4) #Returns 16
PowerShell ilə onluq dəyəri ən yaxın inteqral dəyərə necə qaytarmalı?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
PowerShell ilə müəyyən onluq rəqəmin inteqral hissəsini necə qaytarmalı?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
PowerShell ilə müəyyən rəqəmin dördbucaq kökünü necə qaytarmalı?
[Math]::Sqrt(16) #Returns 4
PowerShell ilə PI konstantasını necə qaytarmalı?
[Math]::Pi #Returns 3,14159265358979
PowerShell ilə təbii loqarifmik bazanı (konstanta e) necə qaytarmalı?
[Math]::E #Returns 2,71828182845905
PowerShell ilə rəqəmin cüt və ya tək olub-olmadığını necə yoxlamalı?
[bool]($number%2)
Hashtables
PowerShell ilə boş haş cədvəlini necə yaratmalı?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
PowerShell ilə maddələrdən ibarət haş cədvəlini necə yaratmalı?
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 ilə maddələri (açar-dəyər cütü) haş cədvəlinə necə əlavə etməli?
$hashtable.Add('Key4', 'Value4')
PowerShell ilə haş cədvəlinin müəyyən dəyərini necə əldə etməli?
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'} |
PowerShell ilə haş cədvəlinin minimum dəyərini necə əldə etməli?
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 ilə haş cədvəlinin maksimum dəyərini necə əldə etməli?
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 ilə haş cədvəlində maddələri necə dəyişməli?
$hashtable.Set_Item('Key1', 'Value1Updated')
PowerShell ilə haş cədvəlində maddələri necə aradan qaldırmalı?
$hashtable.Remove('Key1')
PowerShell ilə haş cədvəlini necə təmizləməli?
$hashtable.Clear()
PowerShell ilə haş cədvəlində müəyyən açarın/dəyərin mövcudluğunu necə yoxlamalı?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
PowerShell ilə haş cədvəldə açarı/dəyəri necə sıralamalı?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
PowerShell ilə boş sıranı necə yaratmalı?
$array = @()
$array = [System.Collections.ArrayList]@()
PowerShell ilə maddələrdən ibarət sıranı necə yaratmalı?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
PowerShell ilə maddələri sıraya necə əlavə etməli?
$array += 'D'
[void]$array.Add('D')
PowerShell ilə sıradakı maddəni necə dəyişməli?
$array[0] = 'Z' # 1st item[0]
PowerShell ilə sıranın ölçüsünü necə yoxlamalı?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
PowerShell ilə sıradakı bir/bir neçə/bütün maddələri necə bərpa etməli?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
PowerShell ilə sıradakı boş maddələri necə aradan qaldırmalı?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
PowerShell ilə sırada maddənin olub-olmadığını necə yoxlamalı?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
PowerShell ilə sırada maddənin indeks nömrəsini necə tapmalı?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
PowerShell sıradakı maddələri əksinə necə sıralamalı?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
PowerShell ilə sıradan təsadüfi maddəni necə əldə etməli?
$array | Get-Random
PowerShell ilə sıranı artan/azalan şəkildə necə sıralamalı?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
PowerShell ilə sıradakı maddələri necə saymalı?
$array.Count
PowerShell ilə sıranı digərinə necə əlavə etməli?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
PowerShell sıradan dublikatları necə tapmalı?
$array = 'A', 'B', 'C', 'C'