Koncepti : Pyetjet më të shpeshta në lidhje me PowerShell.
Këtë listë mund ta përdorni në mënyra të ndryshme :
- Për të kopjuar / ngjitur komandant në një shkrim
- Për të parë shpejt sintaksën e një komande të veçantë
- Për të përmirësuar njohuritë tuaja teknike
- Për të zbuluar komanda të reja
- Për të përgatitur një intervistë për punë
Përditësuar |
2 korrik 2015
|
Autori | powershell-guru.com |
Burimi | albanian.powershell-guru.com |
Kategoritë |
75
|
Pyetjet |
610
|
System
Si të përcaktoni versionin tim të 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 } |
Si të vini në punë PowerShell me një tjetër version për pajtueshmërinë së prapthi?
powershell.exe -Version 2.0
Si të kërkoni një version minimal të PowerShell (3.0 dhe më lart) në një shkrim me PowerShell?
#Requires -Version 3.0
Si të kërkoni privilegje administrative për një shkrim me PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Si të kontrolloni parametrat e një shkrimi me PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Si të merrni informacion për përdoruesin aktual me PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Si të krijoni, modifikoni dhe ringarkoni një profil me 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 |
Si të bëni një pauzë prej 5 sekondash / minutash në një shkrim me PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Si të merrni kohën e fundit të ndezjes me PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Si të merrni tipe përshpejtuesish me 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 |
Si të listoni programet e fillimit me PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Si të çinstaloni një aplikacion me PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Si të bëni një pamje të ekranit të të gjithë desktopit ose të një dritareje aktive me PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Si të mundësoni që mesazhi të ketë rëndësi për radhët MSMQ me PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Si të vendosur politikën e ekzekutimit me PowerShell?
1 2 3 4 5 6 7 8 9 10 11 |
# Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode. Set-ExecutionPolicy -ExecutionPolicy Restricted # AllSigned - Only scripts signed by a trusted publisher can be run. Set-ExecutionPolicy -ExecutionPolicy AllSigned # RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run. Set-ExecutionPolicy -ExecutionPolicy RemoteSigned # Unrestricted - No restrictions - All Windows PowerShell scripts can be run. Set-ExecutionPolicy -ExecutionPolicy Unrestricted |
Si të krijoni një shkurtore me 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() |
Si të gozhdoni ose hiqni nga gozhdimi një program në lidhësen e detyrave me 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') |
Si të hapni Windows Explorer me PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Si të listoni drajverët e pajisjes me PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Si të krijoni një GUID me 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') |
Si të gjeni vendin e drejtorisë së përkohshme për përdoruesin aktual me PowerShell?
[System.IO.Path]::GetTempPath()
Si t’i bashkoheni një rruge dhe një rrugë fëmijësh në një rrugë të vetme me PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Si të listoni të gjitha komandat “Get- *” me PowerShell?
Get-Command -Verb Get
Si të listoni skedarë të veçantë të sistemit me PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Si të montoni dpsje ISO / VHD me PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Si të kontrolloni versionet .NET Framework instaluar me 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 |
Si të kontrolloni nëse versioni .NET Framework 4.5 është instaluar me PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Si të filloni dhe ndaloni një transkript (për të krijuar një regjistrim të sesionit të Windows PowerShell) me PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Si të ndryshoni drejtorinë aktuale në një vend të veçantë me PowerShell?
Set-Location -Path 'C:\scripts'
Si të pastroni ekranin me PowerShell?
Clear-Host
cls # Alias
Si të ndryshoni rezolucionin e ekranit me PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Si të caktoni dritaren e “ekranit të plotë” me PowerShell?
mode.com 300
Si të merrni dimensionet (gjerësinë dhe lartësinë) e një fotoje me 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 } |
Si të merrni çelësin e produktit Windows me 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
Si të merrni “% e Kohës së Përpunimit” (mesatar) aktual në 5 sekondat (10 herë) e fundit me PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Si të ngarkoni mbledhjet me 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') |
Si të kontrolloni mbledhjet aktuale .NET ngarkuar me 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*' } |
Si të gjeni rrugën e GAC (Kasheja Globale e Mbledhjes) me PowerShell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Si të kopjoni rezultate në dërrasën me mbërthecka me PowerShell?
1 |
Get-Process | clip.exe |
Si të merrni përmbajtjen e dërrasës me mbërthecka me PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Si të merrni hotfix-e instaluar me PowerShell?
Get-HotFix -ComputerName $computer
Si të merrni hotfix-e instaluar para / pas një date specifike me 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
Si të kontrolloni nëse një hotfix është instaluar me PowerShell?
Get-HotFix -Id KB2965142
Si të merrni hotfix-e të instaluar në një kompjuter në distancë me PowerShell?
Get-HotFix -ComputerName $computer
Pagefile
Si të merrni informacione të Pagefile me PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Si të merrni madhësinë e rekomanduar (MB) për Pagefile me PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Si të krijoni një Pagefile (4096 MB) në drajvin (D:) me PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Si të fshini një Pagefile në drajvin (C:) me 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
Si të kontrolloni fragmentimin e një drajvi me PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Si të kontrolloni hapësirën e diskut të drajvëve me 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
Si të apni një skedar me PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Si të lexoni një skedar me PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Si të shkruani daljen në një skedar me PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
Si të merrni emrin e plotë të shkrimit aktual me PowerShell?
$MyInvocation.MyCommand.Path
Si të ngjeshni / mbërtheni skedarë me PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
Si të shfryni / zbërtheni skedarë me PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
Si të shihni skedarët në një arkiv ZIP me PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Si të shfaqni madhësinë e një skedari në KB me PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Si të gjeni skedarë më të mëdhenj ose më të vegjël se 1 GB me 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} |
Si të shfaqni emrin e një skedari pa zgjerimin me PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Si të shfaqni zgjerimin e një skedari me PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Si të merrni versionin e skedarit të një skedari me PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Si të merrni hash-in e një skedari me PowerShell?
(Get-FileHash $file).Hash
Si të merrni shumën e shifrave MD5 / SHA1 të një skedari me PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Si të shfaqni skedarët e fshehur me PowerShell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Si të kontrolloni nëse një skedar ka një zgjerim me PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Si të vendosni një skedar si “Vetëm Lexo” me PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Si të ndryshoni atributin “LastWriteTime” në javën e fundit për një skedar me PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Si të krijoni një skedar të ri me PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Si të riemërtoni titullin e një skedari me PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Si të trajtoni / grumbulloni dhe riemërtoni skedarë të shumtë me PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Si të fshini një skedar me PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
Si të shfaqni 10 reshtat e fundit të një skedari me PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Si të zhbllokoni disa skedarë të një dosjeje me PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Si të hiqni reshtat bosh nga një skedar me PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Si të kontrolloni nëse një skedar ekziston me PowerShell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Si të merrni skedarin më të ri / të vjetër të krijuar në skedar me 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 |
Si të hiqni reshta identikë nga një skedar me PowerShell?
1 2 |
Get-Content -Path .\file.txt | Select-Object -Unique # Display Get-Content -Path .\file.txt | Select-Object -Unique | Set-Content -Path .\testing.txt # Save |
Si të merrni skedarë të krijuar pak më shumë se 1 muaj në një skedar me 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 |
Si të merrni skedarë të krijuar pak më shumë se 1 vit në një dosje me 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 |
Si të eksportoni vlerën e një ndryshoreje në një skedar me PowerShell?
Set-Content -Path file.txt -Value $variable
Si të numëroni numrin e skedarëve (* .txt) në një dosje me 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 |
Si të kërkoni një varg brenda shumë skedarëve me PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Si të shfaqni reshtin e parë / të fundit të një skedari me 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 |
Si të shfaqni një numër të caktuar reshti të një skedari me 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 |
Si të numëroni numrin e reshtave të një skedari me PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Si të numëroni numrin e karaktereve dhe fjalët e një skedari me 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 |
Si të shkarkoni një skedar me PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Si të shfaqni rrugën e plotë të një skedari me PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Si të kopjoni një skedar në një dosje me PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Si të kopjoni një skedar në shumë dosje me PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Si të kopjoni fotografi të shumta në një skedar me PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Si të gjeni serverë të Katalogut Global në Drejtorinë Aktive me PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Si të gjeni vende në Drejtorinë Aktive me PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Si të gjeni kontrolluesin aktual të domenit me PowerShell?
(Get-ADDomainController).HostName
Si të gjeni të gjithë kontrolluesit e domenit në një domen me PowerShell?
1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 Get-ADDomainController -Filter * | ForEach-Object -Process {$_.Name} # Solution 2 Get-ADGroupMember 'Domain Controllers' | ForEach-Object -Process {$_.Name} # Solution 3 Get-ADComputer -LDAPFilter '(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))' | ForEach-Object -Process {$_.Name} # Solution 4 [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | ForEach-Object -Process {$_.DomainControllers} | ForEach-Object -Process {$_.Name} |
Si të gjeni dështimet e përsëritjes AD me PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
Si të gjeni jetën e gurit të varrit për pyllin në Drejtorinë Aktive me PowerShell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Si të merrni detajet e një të pylli / domeni në Drejtorinë Aktive me PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Si të gjeni rrugën e enës së “Objekteve të Fshira” në Drejtorinë Aktive me PowerShell?
(Get-ADDomain).DeletedObjectsContainer
Si të mundësoni karakteristikën e Koshit AD të Riciklimit në Drejtorinë Aktive me 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' |
Si të rivendosni një Llogari AD nga Koshi i Riciklimit në Drejtorinë Aktive me PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Si të gjeni rolet FSMO me 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 |
Si të lidheni me një kontrollues specifik domeni me PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'
Si të merrni serverin aktual të identifikimit me PowerShell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Si të kryeni “gpupdate” në një kompjuter me PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Si të krijoni një grup të ri në Drejtorinë Aktive me 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' |
Si të hiqni një grup në Drejtorinë Aktive me PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'
Si të shtoni një përdorues të një grupi në Drejtorinë Aktive me PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Si të hiqni një përdorues nga një grup në Drejtorinë Aktive me PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Si të gjeni grupe bosh (pa asnjë anëtar) në Drejtorinë Aktive me PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Si të numëroni grupe bosh (pa asnjë anëtar) në Drejtorinë Aktive me PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Si të gjeni anëtarët e një grupi në Drejtorinë Aktive me 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' |
Si të merrni anëtarët e një grupi me anëtarë të përsëritur në Drejtorinë Aktive me PowerShell?
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
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 |
Si të zhvendosni një përdorues në një tjetër OU në Drejtorinë Aktive me PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Si të gjeni të gjithë Anëtarët që janë (të mbivendosur) për një përdorues me PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Si të gjeni Anëtarët (emër i shkurtër / i cunguar) për një përdorues me 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 |
Si të ndryshoni Përshkrimin, Zyrën dhe numrin e telefonit për një llogari përdoruesi në Drejtorinë Aktive me 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 |
Si të zhbllokoni një llogari përdoruesi në Drejtorinë Aktive me PowerShell?
Unlock-ADAccount $samAccountName
Si të mundësoni / çaktivizoni një llogari përdoruesi në Drejtorinë Aktive me PowerShell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Si të hiqni një llogari përdoruesi në Drejtorinë Aktive me PowerShell?
Remove-ADUser $samAccountName
Si të rivendosni një fjalëkalim për llogarinë e një përdoruesi në Drejtorinë Aktive me PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
1 2 3 4 5 6 7 |
# Solution 1 : ask password $password = Read-Host -Prompt 'New Password' -AsSecureString # Solution 2 : specify password $password = ConvertTo-SecureString -String 'Q>9xYMw<3?' -AsPlainText -Force Get-ADUser -Filter "samaccountname -like 'helpdeskagent*'" | Set-ADAccountPassword -NewPassword $newpwd -Reset -PassThru | Set-ADuser -ChangePasswordAtLogon $true |
Si të gjeni pronarin e një skedari në Drejtorinë Aktive me 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 |
Si të gjeni OU (Njësinë Organizative) për një përdorues në Drejtorinë Aktive me PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Si të gjeni llogaritë e përdoruesve me aftësi të kufizuara në Drejtorinë Aktive me PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Si të gjeni llogaritë e skaduara të përdoruesve në Drejtorinë Aktive me PowerShell?
Search-ADAccount -AccountExpired
Si të gjeni llogaritë e mbyllura të përdoruesve në Drejtorinë Aktive me PowerShell?
Search-ADAccount -LockedOut
Si të gjeni SID e një llogarie përdoruesi në Drejtorinë Aktive me PowerShell?
(Get-ADUser $user -Properties SID).SID.Value
Si të ktheni një emër përdoruesi në SID në Drejtorinë Aktive me PowerShell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Si të ktheni një SID në emrin e përdoruesit në Drejtorinë Aktive me PowerShell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
Si të ndani Emrin e Dalluar të një llogarie përdoruesi në Drejtorinë Aktive me PowerShell?
1 2 3 |
$dn = 'CN=Powershell Test,OU=TEST,DC=domain,DC=com' $dn.Split(',')[0] # Returns "CN=Powershell Test" $dn.Split(',')[0].Split('=')[1] # Returns "Powershell Test" |
Si të gjeni datën e krijimit / modifikimit të një llogarie përdoruesi në Drejtorinë Aktive me 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 |
Si të merrni rrugën LDAP për një përdorues në Drejtorinë Aktive me PowerShell?
1 2 3 4 |
$searcher = New-Object -TypeName DirectoryServices.DirectorySearcher -ArgumentList ([ADSI]'') $searcher.Filter = "(&(objectClass=user)(sAMAccountName= $user))" $searcher = $searcher.FindOne() $pathLDAP = $searcher.Path |
Si të ndryshoni CN (Emrin Kanonik) për një përdorues në Drejtorinë Aktive me PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Si të gjeni njësinë organizative (OU) prind të një përdoruesi në Drejtorinë Aktive me PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
Si të gjeni pronarin e një përdoruesi (që krijoi llogarinë) në Drejtorinë Aktive me PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Si të ktheni atributin pwdLastSet për një përdorues në Drejtorinë Aktive me PowerShell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Si të testoni kanalin e sigurt mes kompjuterit lokal dhe domenit me PowerShell?
Test-ComputerSecureChannel
Si të riparoni kanalin e sigurt mes kompjuterit lokal dhe domenit me PowerShell?
Test-ComputerSecureChannel -Repair
Si të çaktivizoni një llogari kompjuteri në Drejtorinë Aktive me PowerShell?
Disable-ADAccount $computer
Si të gjeni kompjuterë me sisteme të veçanta operative në Drejtorinë Aktive me PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Get-ADComputer -Filter 'OperatingSystem -eq "CentOS"' Get-ADComputer -Filter 'OperatingSystem -eq "GNU/Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Mac OS X"' Get-ADComputer -Filter 'OperatingSystem -eq "OnTap"' Get-ADComputer -Filter 'OperatingSystem -eq "Red Hat Enterprise Linux Server"' Get-ADComputer -Filter 'OperatingSystem -eq "redhat-linux-gnu"' Get-ADComputer -Filter 'OperatingSystem -eq "Samba"' Get-ADComputer -Filter 'OperatingSystem -eq "Ubuntu"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows NT"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Server"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows XP Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2003"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Business"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Entreprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Ultimate"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server® 2008 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8.1 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 Standard"' |
Organizational Unit (OU)
Si të krijoni një njësi organizative (OU) në Drejtorinë Aktive me PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Si të merrni detajet e një njësie organizative (OU) detajet në Drejtorinë Aktive me PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Si të ndryshoni përshkrimin e një njësie organizative (OU) në Drejtorinë Aktive me 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 |
Si të listoni njësi boshe organizative (OU-të) me 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 } |
Si të gjeni menaxherin e një grupi me PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Si të shkëputni një adresë IP v4 (80.80.228.8) me Regex me 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
Si të shkëputni një adresë MAC (C0-D9-62-39-61-2D) me ndarës “-” me Regex me 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
Si të shkëputni një adresë MAC (C0: D9: 62: 39: 61: 2D) me ndarës “:” me Regex me 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
Si të shkëputni një datë (2015/10/02) me Regex me PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Si të shkëputni një URL (www.powershell-guru.com) me Regex me PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Si të shkëputni një email (user@domain.com) me Regex me 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
Si të shkëputni një “guru” nga vargu shembull me Regex me PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Si të shkëputni “guru.com” nga vargu shembull me Regex me PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Si të shkëputni “powershell-guru.com” nga vargu shembull me Regex me PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Si të shkëputni “123” nga vargu shembull me Regex me PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Si të shkëputni “$” (shenja e dollarit) nga vargu shembull me Regex me PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Si të zëvendësoni një karakter (* .com) me një tjetër (* .fr) në një varg me Regex me PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Si të shpëtoni një varg me Regex me PowerShell?
[regex]::Escape('\\server\share')
Memory
Si të detyroni një koleksion të kujtesës nga kolektori i mbeturinave me PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Si të gjeni madhësinë e RAM të një kompjuteri me PowerShell?
1 2 3 4 5 6 7 8 |
# Solution 1 Get-CimInstance -ClassName 'cim_physicalmemory' | ForEach-Object -Process {$_.Capacity /1GB} # Solution 2 (Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory /1GB # Solution 3 (systeminfo.exe | Select-String -Pattern 'Total Physical Memory:').ToString().Split(':')[1].Trim() |
Date
Si të gjeni datën aktuale me PowerShell?
Get-Date
[Datetime]::Now
Si të shfaqni datën në formate të ndryshme me PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
### DATETIME ### Get-Date -Format D : Tuesday, June 30, 2015 Get-Date -Format f : Tuesday, June 30, 2015 3:22 PM Get-Date -Format F : Tuesday, June 30, 2015 3:22:58 PM Get-Date -Format g : 6/30/2015 3:23 PM Get-Date -Format G : 6/30/2015 3:23:30 PM Get-Date -DisplayHint Date : Tuesday, June 30, 2015 Get-Date -DisplayHint DateTime : Tuesday, June 30, 2015 3:31:21 PM ### DATE ### Get-Date -Format d : 6/30/2015 Get-Date -Format yyyyMMdd : 20150630 Get-Date -UFormat '%d%m%Y' : 30062015 Get-Date -UFormat '%m%d%Y' : 06302015 Get-Date -UFormat '%Y%m%d' : 20150630 Get-Date -UFormat '%d.%m.%Y' : 30.06.2015 Get-Date -UFormat '%m.%d.%Y' : 06.30.2015 Get-Date -UFormat '%Y.%m.%d' : 2015.06.30 Get-Date -UFormat '%d-%m-%Y' : 30-06-2015 Get-Date -UFormat '%m-%d-%Y' : 06-30-2015 Get-Date -UFormat '%Y-%m-%d' : 2015-06-30 Get-Date -UFormat '%d/%m/%Y' : 30/06/2015 Get-Date -UFormat '%m/%d/%Y' : 06/30/2015 Get-Date -UFormat '%Y/%m/%d' : 2015/06/30 ### HOUR ### Get-Date -Format t : 3:23 PM Get-Date -Format T : 3:23:30 PM Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 28 (Minute) Get-Date -Format ss : 30 (Seconds) Get-Date -DisplayHint Time : 3:23:30 PM ### DAY ### Get-Date -Format dddd : Tuesday Get-Date -Format ddd : Tue Get-Date -Format dd : 30 ### MONTH ### Get-Date -Format MMMM : June Get-Date -Format MMM : Jun Get-Date -Format MM : 06 ### YEAR ### Get-Date -Format yyyy : 2015 |
Si të shndërroni një datë (Datetime) deri më sot (Varg) me PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
Si të shndërroni një datë (Varg) deri më sot (Datetime) me PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
Si të llogarisni ndryshimin (numrin e ditëve, orëve, minutave apo sekondave) mes dy datave me 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
Si të krahasoni dy data me 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
Si të zgjidhni një grup datash si “Datetime” me PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Si të nisni dhe të ndaloni një kronometër me PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Si të gjeni ditën aktuale të javës me PowerShell?
(Get-Date).DayOfWeek #Sunday
Si të gjeni datën e djeshme me PowerShell?
(Get-Date).AddDays(-1)
Si të gjeni numrin e ditëve në një muaj (në Shkurt 2015) me PowerShell?
[DateTime]::DaysInMonth(2015, 2)
Si të kuptoni një vit të brishtë me PowerShell?
[DateTime]::IsLeapYear(2015)
Si të listoni zona kohore me PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Si të shifroni (në formatin ASCII) dhe deshifroni një URL me 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 |
Cilat janë ekuivalentet e komandave vendase të rrjetit me 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 |
Si të merrni Adresat IP me PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Si të çaktivizoni adresat IP v6 (IPv6) me PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Si të vërtetoni një adresë IP v4 (IPv4) me PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}
Si të gjeni adresën IP të jashtme me 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 } |
Si të gjeni Hostname nga një adresë IP me PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Si të gjeni adresën IP nga një hostname me PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Si të gjeni FQDN nga një hostname me PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
Si të gjeni konfigurimin e rrjetit (Ip, Subnet, Gateway dhe DNS) me PowerShell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Si të gjeni adresën MAC me PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Si të pingoni një kompjuter me 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) |
Si të kontrolloni nëse një kompjuter është i lidhur në internet me PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Si të kryeni një kërkim “whois” për një faqe interneti me PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Si të gjeni detajet e IP publike (Geolocation) me PowerShell?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Si të kontrolloni nëse një portë është e hapur / mbyllur me PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Si të kryeni “tracert” me PowerShell?
Test-NetConnection www.google.com -TraceRoute
Si të rregulloni profilin e lidhjes të një rrjeti shtëpie me PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Si të shfaqni lidhjet e portës TCP me PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Si të shkurtoni një URL të gjatë në një URL të vogël me PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Si të gjeni parametrat e proksit me PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Si të kontrolloni kashenë e DNS në një kompjuter lokal me PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Si të pastroni kashenë e DNS në një kompjuter lokal me PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Si të pastroni kashenë e DNS në kompjuterët e largët me PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Si të lexoni skedarin e Hotest me PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Si të gjeneroni një fjalëkalim të rastit me PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Si të ndryshoni fjalëkalimin lokal për një administrator në një server në distancë me PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Si të gjeni datën e skadimit të fjalëkalimit të një llogarie në Drejtorinë Aktive me 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
Si të listoni të gjithë printerët për një server specifik me PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Si të listoni të gjitha portet për një server specifik me PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Si të ndryshoni komentin / vendndodhjen e një printeri me 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() |
Si të pastroni (anuloni të gjitha punët) në një printer me PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Si të printoni një faqe testimi për një printer me PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Si të gjeni radhë printimi për printerë me 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
Si të listoni kosheret e regjistrit me PowerShell?
Get-ChildItem -Path Registry::
Si të gjeni vlerat e regjistrit dhe llojet e vlerës me 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) } } } |
Si të listoni nënkyçet e kyçit të regjistrit me 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:\' |
Si të listoni nënkyçet e kyçit të regjistrit në mënyrë të përsëritur me PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Si të gjeni nënkyçet me një emër specifik me PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Si të ktheni vetëm emrin e nënkyçeve të kyçit të regjistrit me PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Si të listoni vlerat e regjistrit me PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Si të lexoni një vlerë të veçantë të regjistrit me PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Si të lexoni një vlerë të veçantë të regjistrit në një kompjuter të largët me 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
Si të krijoni një kyç të ri regjistri me PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'
Si të krijoni një vlerë të regjistrit me PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Si të modifikoni një vlerë ekzistuese të regjistrit me PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Si të fshini një vlerë të regjistrit me PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Si të fshini një kyç të regjistrit me PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Si të testoni nëse një kyç regjistri ekziston me PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'
Si të testoni nëse një vlerë e regjistrit ekziston me PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Si të hiqni karaktere me hapësirë të bardhë nga fillimi i një vargu me PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Si të hiqni karaktere me hapësirë të bardhë nga fundi i një vargu me PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Si të hiqni karaktere me hapësirë të bardhë (nga fillimi dhe fundi) i një vargu me PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()
Si të shndërroni një varg në shkrim me shkronja të mëdha me PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()
Si të shndërroni një varg në shkrim me shkronja të vogla me PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Si të përzgjidhni nënvargun “PowerShell” të vargut “PowershellGuru” me PowerShell?
$string.Substring(0,10)
Si të përzgjidhni nënvargun “Guru” të vargut “PowershellGuru” me PowerShell?
$string.Substring(10)
Si të përzgjedhini numrin “123” të “Powershell123Guru” me PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Si të merrni indeksin e zero-bazë të “feje” të string “PowershellGuru” me PowerShell?
$string.IndexOf('Guru') # 10
Si të kontrolloni nëse një varg është i pavlefshëm ose bosh me PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Si të kontrolloni nëse një varg është nul, bosh, ose përbëhet vetëm nga karakteret me hapësirë të bardhë me PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Si të kontrolloni nëse një varg përmban një shkronjë të veçantë me PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Si të ktheni gjatësinë e një vargu me PowerShell?
$string.Length
Si të lidhni dy vargje me PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Si të përputhni një ose disa kllapa “[ ]” në një varg me PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Si të përputhni një ose disa paranteza “()” në një varg me PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Si të përputhni një ose disa kllapa kaçurrel “{}” në një varg me PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Si të përputhni një ose disa kllapa këndore “& lt; & gt;” në një varg me PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Si të përputhni ndonjë shkronjë të vogële (abc) në një varg me PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Si të përputhni ndonjë shkronjë të madhe (ABC) në një varg me PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Si të përputhni “[p” (p e vogël) në një varg me PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Si të përputhni “[P” (P e madhe) në një varg me PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Si të zëvendësoni një resht me një tjetër resht me PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Si të shndërroni një operacion ndarës në një varg (përqindje) me PowerShell?
(1/2).ToString('P')
Si të zgjidhni vargje që përmbajnë numra me PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Si të përzgjidhni fjalën e fundit të fjalisë me PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Si të gjeni fjalën më të madhe të një fjalie me PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Si të numëroni numrin e herëve që një varg është i pranishëm brenda një fjalie me PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Si të kopjoni çdo karakter të një vargu në një sërë karakteresh me PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Si të shdërroni shkronjën e parë të uppercase të një vargu me PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Si të lëvizni (majtas apo djathtas) një varg me 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 |
Si të shifroni dhe deshifroj një varg në Base64 me 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 |
Si të shndërroni një numër (në dhe nga) binar me 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) |
Si të ktheni vetëm dosjen tefundit prind në një rrugë me PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Si të ktheni vetëm artikullin e fundit në një rrugë me PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Si të listoni metodat e klasës System.Math me PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
Si të ktheni vlerën absolute me PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Si të ktheni këndin sinusi i të cilit është numri i caktuar me PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
Si të ktheni vlerën tavan me PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Si të ktheni vlerën dysheme me PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Si të ktheni logaritmën natyrale (base e) e një numri të caktuar me PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
Si të ktheni logaritmën me bazë 10 të një numri të caktuar me PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
Si për të ktheni maksimumin e dy vlerave me PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Si të ktheni minimumin e dy vlerave me PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Si të ktheni një numër në një vlerë të caktuar katrore me PowerShell?
[Math]::Pow(2,4) #Returns 16
Si të ktheni një vlerë dhjetore në vlerën më të afërt integrale me PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Si të ktheninjë pjesë integrale të një numri të caktuar dhjetor me PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Si të ktheni rrënjën katrore të një numri të caktuar me PowerShell?
[Math]::Sqrt(16) #Returns 4
Si të ktheni PI konstante me PowerShell?
[Math]::Pi #Returns 3,14159265358979
Si të ktheni bazën natyrore logaritmike (e-ja konstante) me PowerShell?
[Math]::E #Returns 2,71828182845905
Si të kontrolloni nëse një numër është i barabartë apo i rastësishëm me PowerShell?
[bool]($number%2)
Hashtables
Si të krijoni një tabelë bosh hashi me PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Si të krijoni një tabelë hashi me artikujt me 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 |
Si të shtoni artikuj (çift kyç-vlerë) në një tabelë hashi me PowerShell?
$hashtable.Add('Key3', 'Value3')
Si të merrni një vlerë të veçantë të një tabele hashi me PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Si të merrni vlerën minimale të një tabele hashi me 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 |
Si të merrni vlerën maksimale të një tabele hashi me 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 |
Si të modifikoni artikuj në një tabelë hashi me PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Si të hiqni sende në një tabelë hashi me PowerShell?
$hashtable.Remove('Key1')
Si të pastroni një tabelë hashi me PowerShell?
$hashtable.Clear()
Si të kontrolloni praninë e një kyçi / vlere të veçantë në një tabelë hashi me PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Si të renditni sipas kyçit / vlerës në një tabelë hashi me PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Si të krijoni një rrjet bosh me PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()
Si të krijoni një grup me artikuj me PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Si të shtoni artikuj në një grup me PowerShell?
$array += 'D'
[void]$array.Add('D')
Si të modifikoni një objekt në një grup me PowerShell?
$array[0] = 'Z' # 1st item[0]
Si të kontrolloni madhësinë e një grupi me PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Si të rifitoni një artikull / disa / të gjithë artikujt në një grup me PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Si të hiqni artikuj bosh në një grup me PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Si të kontrolloni nëse një objekt ekziston në një grup me PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Si të gjeni indeksin e numrit të një artikulli në një grup me PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Si të ktheni rendin e artikujve në një grup me PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Si të gjeneroni një artikull të rastit nga një grup me PowerShell?
$array | Get-Random
Si të renditni një grup në rend ngjitës / zbritës me PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Si të numëroni numrin e artikujve në një grup me PowerShell?
$array.Count
Si të shtoni një grup në një tjetër me PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Si të gjeni kopje identike nga një grup me PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
Si të hiqni kopje identike nga një grup me PowerShell?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
Si të krijoni një grup me artikuj duke filluar me një prefiks (“user01”, “user02”, …, “user10”) me PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Si të listoni ACL e një përdoruesi AD me PowerShell?
(Get-Acl -Path "AD:\$dn").Access
Si të listoni ACL e një dosje me 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
Cilat janë llojet më të zakonshme të të dhënave në 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 |
Si të gjeni vlerat minimale dhe maksimale të disa variablave të tipit me 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 |
Si të testoni tipin e të dhënave me PowerShell?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
Si të krijoni një ndryshore Here-String me PowerShell?