Fikradda : Su’aalaha ku saabsan Powershell inta badan la weydiiyay.
Waxaad isticmaali kartaa liiskan siyaabo kala duwan :
- Si aad nuqul ka / amarrada Jinka galay script ah
- Si deg deg ah arki while oo amarkiisa ka gaar ah
- Si loo hagaajiyo aqoon farsamo aad
- Si aad u ogaan amarrada cusub
- Si aad u diyaariso wareysi shaqo
Updated |
July 02, 2015
|
Author | powershell-guru.com |
Source | somali.powershell-guru.com |
Categories |
75
|
Su’aalo |
610
|
System
Sida loo ogaado aan version of 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 } |
Sida loo ordo PowerShell in version kale oo waafaqsan u socdeen?
powershell.exe -Version 2.0
Sidee u baahan version yar PowerShell (3.0 oo ka sareeya) script ah oo la PowerShell?
#Requires -Version 3.0
Sidee ay u baahan yihiin mudnaanta maamul u script ah oo la PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Sida loo hubiyo xuduudaha ka script ah oo la PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Sidee si ay u helaan macluumaad loogu talagalay user hadda la PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Sida loo abuuro, edit, iyo Reload profile ah la PowerShell?
1 2 3 4 5 6 7 8 9 |
# Create New-Item -Type file -Force $profile # Edit notepad.exe $profile # Reload (without restarting Powershell) & $profile .$profile |
Sida loo sameeyo hakin ah oo 5 ilbiriqsi / daqiiqo in script ah oo la PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Sida loo helo markii ugu danbeysay ee ay la boot PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Sidee loo helaa Sheelare nooca la 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 |
Sida loo qor barnaamijyada xawaaladaha la PowerShell ah?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Sida loo uninstall codsi la PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Sida loo qaado shaashada ah desktop oo dhan ama uusan xirmin suuqa firfircoon la PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Sidee loo helaa count fariin u MSMQ safafka la PowerShell ah?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Sida loo dhigay siyaasadda dil la PowerShell ah?
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 |
Sida loo abuuro toobiye ah la 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() |
Sida loo wareemo ama unpin barnaamij lagu Taskbar la 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') |
Sida loo furo Explorer Windows ah la PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Sidee inay taxaan wadayaasha qalab la PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Sida loo abuuro Pario ah la PowerShell?
1 2 3 4 5 6 7 8 9 10 11 |
# Empty GUID $guid = [GUID]::Empty # New GUID (lower case by default) $guid = [GUID]::NewGuid() # New GUID (upper case) $guid = ([GUID]::NewGuid()).ToString().ToUpper() # New GUID with a specific value $guid = [GUID]('bc4ad3d3-d704-4bd0-843f-d607fbbc4cd7') |
Sida loo helo meesha uu buugga ku meel gaar ah ee user hadda la PowerShell?
[System.IO.Path]::GetTempPath()
Sidee inuu ku biiro ah waddada iyo jidka ilmo galay mid ka mid ah jidka kaliya la PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Sidee inay taxaan oo dhan cmdlets “bensiin *” la PowerShell?
Get-Command -Verb Get
Sidee inaad Liiska ku fayl nidaam gaar ah la PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Sidee Buur ISO files / VHD la PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Sida loo hubiyo .NET Framework versions rakibay la 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 |
Sidee si ay u hubiso haddii version .NET Framework 4.5 la geliyo la PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Sidee si ay u bilaabaan oo ay joojiyaan qoraalka ah (in la abuuro rikoor ah fadhiga Windows PowerShell) la PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Sida loo beddelo buugga hadda meel gaar ah la PowerShell?
Set-Location -Path 'C:\scripts'
Sida loo kala cadeeyo shaashada la PowerShell?
Clear-Host
cls # Alias
Sida loo beddelo xal bandhigay la PowerShell ah?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Sida loo dhigay “shaashad buuxda” uu furmo suuqa la PowerShell?
mode.com 300
Sidee si ay u helaan cabbir (ballaca iyo dhererka) ee sawir leh 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 } |
Sida loo helo furaha Windows alaabta la 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
Sidee si ay u helaan “Time% processor” hadda (celcelis) ee 5 ilbiriqsi ee la soo dhaafay (10 jeer) la PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Sida loo shuban shirarkeeda la 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') |
Sida loo hubiyo shirarkeeda .NET hadda ku raran 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*' } |
Sida loo helo GAC (Global Golaha khasnado) Jidka la PowerShell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Sida loo nuqul ka natiijooyinka si clipboard la PowerShell?
1 |
Get-Process | clip.exe |
Sidee loo helaa content ee clipboard la PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Sidee loo helaa hotfixes ku rakiban la PowerShell?
Get-HotFix -ComputerName $computer
Sidee loo helaa hotfixes ku rakibay wixii ka horreeyey / ka dib taariikhda gaar ah la 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
Sidee si ay u hubiso haddii hotfix ah la geliyo la PowerShell?
Get-HotFix -Id KB2965142
Sidee loo helaa hotfixes ku rakiban computer fog la PowerShell?
Get-HotFix -ComputerName $computer
Pagefile
Sidee si ay u helaan macluumaad Pagefile la PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Sida loo helo xajmiga talinayaa (MB) ee Pagefile la PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Sida loo abuuro Pagefile ah (4096 MB) on (D 🙂 kaxayn la PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Sidee in ay tirtirto Pagefile ku (C 🙂 kaxayn la 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
Sida loo hubiyo midnimo la’aan ah oo gaari ah la PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Sida loo hubiyo meel disk ee drives la 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
Sida loo furo file ah la PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Sida loo akhriyo file ah oo la PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Sida loo qoro wax soo saarka si ay u file ah oo la PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
Sidee loo helaa fullname oo ka mid ah file script hadda la PowerShell?
$MyInvocation.MyCommand.Path
Sidee ku cadaadisaa / files zip la PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
Sida loo uncompress / files siibka la PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
Sidee si ay u arkaan files ee archive ZIP la PowerShell ah?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Sida loo soo bandhigo size ee file a in la KB PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Sida loo helo faylasha weyn ama ka yar 1 GB la 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} |
Sida loo soo bandhigo magaca file ah oo aan kordhin la PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Sida loo soo bandhigo qandaraas kordhin ah oo file ah oo la PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Sidee loo helaa version file ah file ah oo la PowerShell ah?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Sidee loo helaa hash ee file ah la PowerShell?
(Get-FileHash $file).Hash
Sidee si ay u helaan dalbatay MD5 / SHA1 ee file ah oo la PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Sida loo soo bandhigo faylasha qarsoon la PowerShell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Sidee si ay u hubiso haddii file ah ayaa qandaraaska u kordhiyey PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Sida loo dhigay file ah sida “Kaliya akhri” la PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Sida loo beddelo “LastWriteTime” sifo in toddobaadkii la soo dhaafay u file ah oo la PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Sida loo abuuro file cusub PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Sida loo magaca file ah oo la PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Sida loo badan / Dufcaddii magaca files kala duwan leh PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Sidee in ay tirtirto file ah la PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
Sida loo soo bandhigo 10-ka khadadka ugu dambeeyay ee file ah oo la PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Sida loo unblock faylasha dhowr ah oo gal la PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Sidee in ay ka saarto khadadka madhan ka file ah la PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Sidee si ay u hubiso haddii file ka jira la PowerShell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Sidee loo helaa / da’da weyn file cusub ee abuuray gal ah la 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 |
Sida loo ka file ah la PowerShell saarto khadadka nuqul?
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 |
Sidee loo helaa faylasha abuuray dheeraad ah ama ka yar 1 bil galka ah la 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 |
Sidee loo helaa faylasha abuuray dheeraad ah ama ka yar 1 sano galka ah la 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 |
Sida loo dhoofin qiimaha variable ah in file ah oo la PowerShell?
Set-Content -Path file.txt -Value $variable
Sida loo tiriyo tirada faylasha (* .txt) galka ah la 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 |
Sida loo raadin xarig ah gudaha files kala duwan leh PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Sida loo soo bandhigaan / line ugu horeysay ee la soo dhaafay ee file ah oo la 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 |
Sida loo soo bandhigo tirada gaar ah line of file ah la 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 |
Sida loo tirin tirada layman file ah oo la PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Sida loo tiriyo tirada jilayaasha iyo erayadii file ah oo la 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 |
Sida loo file la PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Sida loo soo bandhigo Jidka buuxda ee file ah la PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Sida loo nuqul ka mid file in gal ah la PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Sida loo nuqul ka mid file inay fayl badan la PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Sida loo nuqul ka files badan in hal folder la PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Sida loo helo server Catalog Global ee Directory firfircoon la leh PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Sida loo helo goobaha in Directory firfircoon la leh PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Sida loo helo qofka xukuma ee domain hadda la PowerShell?
(Get-ADDomainController).HostName
Sida loo helo oo dhan ilaaliyaal domain in domain ah oo la PowerShell ah?
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} |
Sida loo helo guuldarrada taranka AD la PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Sida loo helo faahfaahin kaynta / domain ee Directory firfircoon la leh PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Sidee loo helaa Jidka “Waxyaabaha tirtiray” weelka in Directory firfircoon la leh PowerShell?
(Get-ADDomain).DeletedObjectsContainer
Sidee si ay awood AD feature Recycle Bin ee Directory firfircoon la leh 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' |
Sida loo soo celiyo Account AD ka Recycle Bin ee Directory firfircoon la leh PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Sida loo helo doorarka FSMO la 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 |
Sidee in ay ku xidhmaan xukuma gaar ah domain la PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'
Sidee loo helaa server ka logon hadda la PowerShell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Sida loo sameeyo “gpupdate” kombiyuutarka ah la PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Sida loo abuuro koox cusub ee Directory firfircoon la leh 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' |
Sidee in ay ka saarto koox ee Directory firfircoon la leh PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'
Sida loo dar user a si koox ee Directory firfircoon la leh PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Sidee in ay ka saarto user ka koox ee Directory firfircoon la leh PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Sida loo helo kooxo madhan (xubnaha lahayn) in Directory firfircoon la leh PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Sidee loo tiriyo kooxaha madhan (xubnaha lahayn) in Directory firfircoon la leh PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Sidee si ay u helaan xubno ka mid ah koox ee Directory firfircoon la leh PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Solution 1 Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname} # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
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 |
Sidee u dhaqaaqo user a si shaqeeya kale ee Directory firfircoon la leh PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Sida loo helo dhammaan xubnaha in ay yihiin (Nested) ee user a la PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Sidee loo helaa Xubnaha (gaaban magaca / keenin) ee user a la PowerShell?
(Get-ADUser $user -Properties MemberOf).MemberOf | ForEach-Object -Process {($_ -split ',')[0].Substring(3)} | Sort-Object
1 2 |
Set-ADUser $samAccountName -DisplayName 'DisplayName' -GivenName 'Test' -Surname 'Powershell' -DisplayName 'Test Powershell' Rename-ADObject $dn -NewName 'Test Powershell' #FullName |
Sidee in la beddelo Description, Xafiiska, iyo lambarka telefoonka xisaab user ee Directory firfircoon la leh 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 |
Sida loo furo xisaab user in Directory firfircoon la leh PowerShell ah?
Unlock-ADAccount $samAccountName
Sidee si ay awood / gab koonto cusub Directory firfircoon la leh PowerShell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Sidee in ay ka saarto koonto cusub Directory firfircoon la leh PowerShell?
Remove-ADUser $samAccountName
Sida loo joojiyo oo sirta ah xisaab mid user in Directory firfircoon la leh 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 |
Sida loo joojiyo oo sirta ah dhowr xisaab user (bulk) ee Directory firfircoon la leh 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 |
Sida loo helo milkiilaha file a in Directory firfircoon la leh 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 |
Sida loo helo shaqeeya ah (Unit ee hayadaha) ee ah user in Directory firfircoon la leh PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Sida loo helo xisaab user dadka naafada ah ee Directory firfircoon la leh PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Sida loo helo xisaab user dhacay in Directory firfircoon la leh PowerShell?
Search-ADAccount -AccountExpired
Sida loo helo xisaab user qufulan ee Directory firfircoon la leh PowerShell?
Search-ADAccount -LockedOut
Sida loo helo SID ee koonto cusub Directory firfircoon la leh PowerShell?
(Get-ADUser $user -Properties SID).SID.Value
Sida loo badalo username ah in SID in Directory firfircoon la leh PowerShell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Sida loo badalo SID ah in username in Directory firfircoon la leh PowerShell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
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" |
Sida loo helo taariikhda abuurniinta / beddelaad koonto cusub Directory firfircoon la leh 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 |
Sida loo helo waddo LDAP ah user in Directory firfircoon la leh PowerShell ah?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
Sida loo beddelo CN (qaadanin Name) ee ah user in Directory firfircoon la leh PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Sidee loo helaa Unugga ururka (OU) waalidka ee ku user in Directory firfircoon la leh PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
Sida loo helo milkiilaha a user (yaa abuuray account) ee Directory firfircoon la leh PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Sida loo badalo sifo PwdLastSet u user in Directory firfircoon la leh PowerShell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Sidee si ay u tijaabiso channel ka aamin ka dhexeeya computer maxalliga ah iyo domain la PowerShell?
Test-ComputerSecureChannel
Sidee si ay u cusboonaysiiyaan channel ka aamin ka dhexeeya computer maxalliga ah iyo domain la PowerShell?
Test-ComputerSecureChannel -Repair
Sida loo gab account computer ee Directory firfircoon la leh PowerShell ah?
Disable-ADAccount $computer
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)
Sida loo abuuro Unit ah ururada (OU) ee Directory firfircoon la leh PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Sidee loo helaa Unit ururka (OU) tafaasiisha Active Directory la PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Sida loo beddelo sharaxaad ka mid ah Unit ah ururada (OU) ee Directory firfircoon la leh 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 |
Sidee inay taxaan qaybaha haya’adda madhan (oo halis ah) la 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 } |
Sida loo helo tababare u ahaa koox la PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Sida loo soo saaro ah V4 Ciwaanka IP: ga (80.80.228.8) la Regex la 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
Sida loo soo saaro cinwaan MAC (C0-D9-62-39-61-2D) la separator “-” la Regex la 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
Sida loo soo saaro cinwaan MAC (C0: D9: 62: 39: 61: 2D) la separator “:” la Regex la 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
Sida loo soo saaro taariikh (10/02/2015) la Regex la PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Sida loo soo saaro URL ah (www.powershell-guru.com) la Regex la PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Sida loo soo saaro email ah (user@domain.com) la Regex la 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
Sida loo soo saaro “Galliani” ka tusaale xarig la Regex la PowerShell ah?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Sida loo soo saaro “guru.com” ka tusaale xarig la Regex la PowerShell ah?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Sida loo soo saaro “powershell-guru.com” ka tusaale xarig la Regex la PowerShell ah?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Sida loo soo saaro “123” oo ka tusaale xarig la Regex la PowerShell ah?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Sida loo soo saaro “$” (calaamad dollar) ka tusaale xarig la Regex la PowerShell ah?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Sida loo badalo qof (* .com) iyo mid kale (* .fr) oo xarig ah la Regex la PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Sidee si ay uga baxsadaan xarig ah la Regex la PowerShell?
[regex]::Escape('\\server\share')
Memory
Sida loo qasbi ah ururinta xasuusta by ururiyaha qashinka la PowerShell ah?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Sidee loo helaa size RAM ee kombiyuutar la PowerShell ah?
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
Sida loo helo taariikhda hadda la PowerShell?
Get-Date
[Datetime]::Now
Sida loo soo bandhigaan taariikhda qaabab kala duwan la 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 |
### DATE ### Get-Date -Format d : 15/04/2015 Get-Date -Format D : 15 April 2015 Get-Date -Format f : 15 April 2015 14:57 Get-Date -Format F : 15 April 2015 14:57:34 Get-Date -Format g : 15/04/2015 14:57 Get-Date -Format G : 15/04/2015 14:57:34 Get-Date -Format yyyyMMdd : 20150415 Get-Date -UFormat '%d%m%Y' : 15042015 Get-Date -UFormat '%m%d%Y' : 04152015 Get-Date -UFormat '%Y%m%d' : 20150415 Get-Date -UFormat '%d%m%Y' : 15-04-2015 Get-Date -UFormat '%m%d%Y' : 04-15-2015 Get-Date -UFormat '%Y%m%d' : 2015-04-15 ### HOUR ### Get-Date -Format t : 15:31 Get-Date -Format T : 15:31:44 Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 57 (Minute) Get-Date -Format ss : 34 (Seconds) Get-Date -DisplayHint Time : 15:31:44 ### DAY ### Get-Date -Format dddd : Wednesday Get-Date -Format ddd : Wed Get-Date -Format dd : 15 ### MONTH ### Get-Date -Format MMMM : April Get-Date -Format MMM : Apr Get-Date -Format MM : 04 ### YEAR ### Get-Date -Format yyyy : 2015 |
Sida loo badalo taariikh (Datetime) si ay taariikh (String) la PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
Sida loo badalo taariikh (String) si ay taariikh (Datetime) la PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
Sidee si ay u xisaabiso faraqa u (Tirada Maalmaha, Saacadaha, Minutes, ama seconds) inta u dhaxaysa laba taariikhaha la 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
Sidee inay is barbar dhigaan laba taariikhaha la 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
Sida loo kala sooco soo diyaariyeen ah oo timir ah sida “Datetime” la PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Sidee si ay u bilaabaan oo ay joojiyaan stopwatch ah la PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Sidee loo helaa maalinta hadda ee toddobaadka la PowerShell?
(Get-Date).DayOfWeek #Sunday
Sida loo helo taariikhda shalay la PowerShell?
(Get-Date).AddDays(-1)
Sida loo helo tirada maalmaha bisha (in February 2015) la PowerShell?
[DateTime]::DaysInMonth(2015, 2)
Sida loo ogaado sano ah u boodboodi la PowerShell?
[DateTime]::IsLeapYear(2015)
Sidee inay taxaan goobaha waqtiga la PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Sida loo encode (in qaab ASCII) oo uu kelmadaha URL ah la 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 |
Waa maxay u dhigma of amarrada network hooyo la 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 |
Sidee loo helaa cinwaanada IP la PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Sida loo gab IP address v6 (IPv6) la PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Sida loo ansixiyo V4 Ciwaanka IP: ga ah (IPv4) la PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}
Sida loo helo cinwaanka IP dibadda la 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 } |
Sida loo helo Hostname ka Ciwaanka IP: ga la PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Sida loo helo cinwaanka IP ka Hostname ah la PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Sida loo helo FQDN ka Hostname ah la PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
Sida loo helo qaabeynta network (IP, Subnet, Gateway, iyo DNS) la PowerShell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Sida loo helo cinwaanka MAC la PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Sida loo Ping kombiyuutar la 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) |
Sidee si ay u hubiso haddii computer la xiran internetka la PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Sida loo sameeyo a “WHOIS” Lookup u website qaba PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Sida loo helo faahfaahinta IP dadweynaha (geolocation) la PowerShell?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Sidee si ay u hubiso haddii dekedda ah u furan yahay / la xidhay la PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Sida loo sameeyo “tracert” la PowerShell?
Test-NetConnection www.google.com -TraceRoute
Sida loo hagaajin la xidhiidha profile network guri la PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Sidee si ay u muujiyaan isku xirka dekedda TCP la PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Sida loo soo gaabin URL dheer URL yar la PowerShell galay?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Sida loo helo goobaha wakiil la PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Sida loo hubiyo khasnado DNS ee kombiyuutarka deegaanka la PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Sida loo kala cadeeyo khasnado DNS on computer maxali ah oo la PowerShell ah?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Sida loo kala cadeeyo khasnado DNS on kombiyuutarada fog la PowerShell ah?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Sida loo akhriyo ciidammadu ku soo gudbin la PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Sidee in ay curiyaan sirta ah random la PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Sida loo beddelo sirta ah ee degmadaada maamulka on server fog la PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Sida loo helo taariikhda uu dhacayo password koonto ku Directory firfircoon la leh PowerShell?
1 2 3 4 5 6 7 8 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser -Identity $user -Properties 'msDS-UserPasswordExpiryTimeComputed').'msDS-UserPasswordExpiryTimeComputed') # Solution 2 Get-Date -Date ((Get-ADUser $user -Properties 'msDS-UserPasswordExpiryTimeComputed' | Select-Object -Property @{ Name = 'ExpiryDate' Expression = {[DateTime]::FromFileTime($_.'msDS-UserPasswordExpiryTimeComputed')} }).ExpiryDate)-Format 'F' |
Printers
Sida loo qor dhamaan madbacadaha ee server gaar ah la PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Sidee inay taxaan oo dhan dekedaha ee server gaar ah la PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Sida loo beddelo comment / goobta printer ah la 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() |
Sidee loo daahiriyo (diido dhamaan shaqooyinka) lagu daabaco la PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Sida loo daabacan page baaritaan loogu talagalay in printer ah la PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Sida loo helo safafka print u madbacadaha la 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
Sidee inay taxaan finan diiwaanka la PowerShell?
Get-ChildItem -Path Registry::
Sida loo helo qiimaha diiwaanka iyo noocyada qiimaha la 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) } } } |
Sida loo liiska muhiim ah subkeys la 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:\' |
Sidee inay taxaan subkeys muhiim ah diiwaanka hab recursive la PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Sida loo helo subkeys la magac gaar ah la PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Sidee inuu ku soo laabto oo keliya magaca subkeys diiwaanka la PowerShell ah?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Sida loo qor qiimaha diiwaanka la PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Sida loo akhriyo qiimo gaar ah diiwaanka la PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Sida loo akhriyo qiimo gaar ah diiwaanka kombiyuutarka fog la 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
Sidee si ay u abuuraan fure cusub oo diiwaanka la PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'
Sida loo abuuro qiimaha diiwaanka la PowerShell ah?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Sidee inuu wax ka beddelo lagu qiimeeyay diiwaangelinta ee hadda jira la PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Sidee in ay tirtirto qiimaha diiwaanka la PowerShell ah?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Sidee in ay tirtirto muhiim ah diiwaanka la PowerShell ah?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Sidee u ah inay tijaabiso hadii muhiim ah diiwaanka ah la PowerShell ka jira?
Test-Path -Path 'HKCU:\Software\MyApplication'
Sidee u ah inay tijaabiso hadii qiimaha diiwaanka ka jira la PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Sidee in ay ka saarto cad-meel characters tan iyo bilowgii xarig ah la PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Sidee in ay ka saarto cad-meel characters ka dhamaadka xarig ah la PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Sidee in ay ka saarto cad-meel characters (bilow ilaa dhamaad) ee xarig ah la PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()
Sida loo badalo xarig ah in kiiska sare leh PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()
Sida loo badalo xarig ah in ay hoos u dhacdo in la PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Sidee in ay doortaan substring “PowerShell” ee xadhigga “PowerShellGuru” la PowerShell?
$string.Substring(0,10)
Sidee in ay doortaan substring ah “Guru” ee xadhigga “PowerShellGuru” la PowerShell?
$string.Substring(10)
Sidee in ay doortaan tirada “123” oo ah “PowerShell123Guru” la PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Sidee loo helaa index ah eber ku salaysan ee “Guru” ee “PowerShellGuru” xarig la PowerShell?
$string.IndexOf('Guru') # 10
Sidee si ay u hubiso haddii xarig ah waa waxba kama ama madhan la PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Sidee si ay u hubiso haddii xarig ah waa waxba, madhan, ama kooban yahay oo kaliya cad-meel characters la PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Sidee si ay u hubiso haddii xarig ah ku jira warqad gaar ah oo la PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Sidee inuu ku soo laabto dhererka xarig ah la PowerShell?
$string.Length
Sida loo concatenate laba xadhig la PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Sida loo dhigma hal ama dhowr qaansada “[]” in xarig ah la PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Sida loo dhigma hal ama dhowr parentheses “()” oo xarig ah la PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Sida loo dhigma hal ama dhowr qaansada ku kuweyga “{}” in xarig ah la PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Sida loo dhigma hal ama dhowr qaansada ku xagal “<>” in xarig ah la PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Sida loo dhigma wax xarfaha (ABC) oo xarig ah la PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Sida loo dhigma wax upperletters (ABC) oo xarig ah la PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Sida loo dhigma “[p” (p kiiska hoose) in xarig ah la PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Sida loo dhigma “[P” (P kiiska sare) in xarig ah la PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Sida loo bedelo line ku haysta xadhig kale la PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Sida loo badalo howlgalka kala qaybsameen in xarig ah (boqolkiiba) la PowerShell?
(1/2).ToString('P')
Sida loo kala sooco xadhig ka kooban tirooyin leh PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Sidee in ay doortaan hadalka ee la soo dhaafay xukun la PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Sida loo helo erayga ugu weyn ee xukun la PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Sida loo tirin tirada jeer xarig ah waa hadiyad xukun la PowerShell gudahooda?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Sida loo nuqul ka qof kasta oo xarig ah in qof la dagaallamaan ah la PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Sida loo badalo xarafka ugu horeeya si ay u waawayn ee xarig ah la PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Sida loo gashto (bidix ama midig) oo xarig ah la 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 |
Sida loo encode iyo kelmadaha xarig ah in Base64 la 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 |
Sida loo badalo dhawr ah (iyo ka) binary la 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) |
Sidee inuu ku soo laabto kaliya folder waalidka ee la soo dhaafay waddo la PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Sidee inuu ku soo laabto kaliya shayga ugu danbeysay ee ay waddo la PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Sida loo qor hababka fasalka System.Math la PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
Sidee inuu ku soo laabto qiimaha buuxda la PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Sidee inuu ku soo laabto ka leexdo oo Culumida Soomaaliyeed waa tirada cayiman la PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
Sidee inuu ku soo laabto qiimaha saqafkiisa PowerShell ah?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Sidee inuu ku soo laabto qiimaha dabaqa la PowerShell ah?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Sidee inuu ku soo laabto dabiiciga ah (saldhig e) logarithm tirada cayiman la PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
Sidee inuu ku soo laabto saldhigga 10 logarithm tiro cayiman la PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
Sidee inuu ku soo laabto ugu badnaan laba qiimaha la PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Sidee inuu ku soo laabto ugu yaraan laba qiimaha la PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Sidee inuu ku soo laabto tiro sara kiciyey si ay awood cayiman la PowerShell?
[Math]::Pow(2,4) #Returns 16
Sidee inuu ku soo laabto qiimaha tobanle in qiimaha ugu dhow muhiim ah la PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Sidee inuu ku soo laabto qaybta muhiim ah oo tiro cayiman jajab tobanle leh PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Sidee inuu ku soo laabto xididka laba jibbaaran tiro cayiman la PowerShell?
[Math]::Sqrt(16) #Returns 4
Sidee inuu ku soo laabto joogto PI la PowerShell ah?
[Math]::Pi #Returns 3,14159265358979
Sidee inuu ku soo laabto saldhigga logardam dabiiciga ah (joogto ah e) la PowerShell?
[Math]::E #Returns 2,71828182845905
Sidee si ay u hubiso haddii tiro xitaa ama cajiib ah la PowerShell?
[bool]($number%2)
Hashtables
Sida loo abuuro hashtable madhan la PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Sida loo abuuro hashtable qaba waxyaabaha la 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 |
Sidee ku darto waxyaabaha (labada ciyaaryahan muhiim ah qiimaha) si hashtable ah la PowerShell?
$hashtable.Add('Key3', 'Value3')
Sida loo helo qiimaha gaarka ah ee hashtable ah la PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Sida loo helo qiimaha ugu yar ee hashtable ah la 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 |
Sida loo helo qiimaha ugu badan ee hashtable ah la 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 |
Sidee inuu wax ka beddelo alaabta ee hashtable ah la PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Sidee inuu ka saaro waxyaabaha ku hashtable ah la PowerShell?
$hashtable.Remove('Key1')
Sida loo kala cadeeyo hashtable ah la PowerShell?
$hashtable.Clear()
Sida loo hubiyo jiritaanka muhiim ah / qiimaha gaarka ah ee hashtable ah la PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Sida loo kala sooco by muhiimka ah / qiimaha ee hashtable ah la PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Sidee si ay u abuuraan dagaal isugu diyaariyeen madhan la PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()
Sidee si ay u abuuraan dagaal isugu diyaariyeen la alaabta la PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Sida loo waxyaabaha lagu daro in la dagaallamaan la PowerShell?
$array += 'D'
[void]$array.Add('D')
Sidee inuu wax ka beddelo shay soo diyaariyeen la PowerShell?
$array[0] = 'Z' # 1st item[0]
Sida loo hubiyo size ee soo diyaariyeen la PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Sida loo soo ceshano hal shay / dhowr ah oo dhan alaabta / diyaariyeen la PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Sidee inuu ka saaro waxyaabaha madhan soo diyaariyeen la PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Sidee si ay u hubiso haddii shay jirta soo diyaariyeen la PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Sida loo helo tirada index shay soo diyaariyeen la PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Sidee u ah dib-amarka ah waxyaabaha soo diyaariyeen la PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Sidee si ay wax nasiib ah laga soo diyaariyeen la PowerShell?
$array | Get-Random
Sida loo kala sooco soo diyaariyeen ah oo kor u kacaya / hab soo degaya la PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Sida loo tirin tirada alaabta soo diyaariyeen la PowerShell?
$array.Count
Sida loo dar soo diyaariyeen ah midka kale kula PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Sida loo helo tus ka soo diyaariyeen la PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
Sida loo ka la dagaallamaan la PowerShell saarto tus?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
Sidee si ay u abuuraan dagaal isugu diyaariyeen la alaabta laga bilaabo horgale (“user01”, “user02”, … “user10”) la PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Sidee inaad Liiska ku gil gilay warka ee user AD la PowerShell?
(Get-Acl -Path "AD:\$dn").Access
Sidee inaad Liiska ku gil gilay warka of gal ah la PowerShell?
(Get-Acl -Path C:\scripts).Access
1 |
((Get-Acl -Path "AD:\$dn").Access | Select-Object -Property IdentityReference | Where-Object -FilterScript {$_.IdentityReference -match 'Admin'} | Get-Unique | ForEach-Object -Process {$_.IdentityReference}).Value |
Variables
Waa maxay noocyada macluumaadka ugu badan ee la PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[bool]$variable = $true [byte]$variable = ('0x10') [char]$variable = 0x260E [datetime]$variable = Get-Date [decimal]$variable = 1.89 [double]$variable = 1.89 [float]$variable = 1.89 [guid]$variable = 'b19b2a2e-ce1b-4b62-844f-ac8829ffbe8f' [int16]$variable = -32767 [int32]$variable = -2147483647 [int64]$variable = -9223372036854775807 [string]$variable = 'test' [uint16]$variable = 32767 [uint32]$variable = 2147483647 [uint64]$variable = 9223372036854775807 |
Sida loo helo ugu yaraan iyo ugu badnaan qiimaha doorsoomeyaasha nooca qaar ka mid ah la PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
[int] (integer) # int16 : MIN:-32768 MAX:32767 'MIN:{1:D} MAX:{0:D}' -f [int16]::MaxValue, [int16]::MinValue # int32 : MIN:-2147483648 MAX:2147483647 'MIN:{1:D} MAX:{0:D}' -f [int32]::MaxValue, [int32]::MinValue # int64 : MIN:-9223372036854775808 MAX:9223372036854775807 'MIN:{1:D} MAX:{0:D}' -f [int64]::MaxValue, [int64]::MinValue [uint] (u = unsigned, only positive numbers) # int16 : MAX:65535 'MAX:{0:D}' -f [uint16]::MaxValue # int32 : MAX:4294967295 'MAX:{0:D}' -f [uint32]::MaxValue # int64 : MAX:18446744073709551615 'MAX:{0:D}' -f [uint64]::MaxValue |
Sidee si ay u tijaabiso datatype la PowerShell?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
Sida loo abuuro Halkan-darrooyin is variable la PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Without variable $hereString = @" My first name is Test My last name is Powershell "@ # With variable $firstName = 'Test' $lastName = 'Powershell' $hereString = @" My first name is ${firstName} My last name is ${lastName} "@ |
Sida loo abuuro variable ah oo la PowerShell?
$powershellGuru = 'Hello'
Sida loo abuuro variable ah oo joogto ah la PowerShell?
Set-Variable -Name powershellGuru -Value 2015 -Option Constant
Sida loo abuuro variable caalami ah oo PowerShell?
$Global:powershellGuru = 'Hello'
Sida loo akhriyo variable ah oo la PowerShell?
$powershellGuru = 'Hello' # Create