Efni: Algengustu spurningar varðandi PowerShell.
Þú getur notað þennan lista í mismunandi vegu:
- Til að afrita / líma skipanir í skriftu
- Til að sjá fljótt setningafræði tiltekinnar skipunar
- Til að bæta tæknilega kunnáttu þína
- Að uppgötva nýjar skipanir
- Til að undirbúa þig undir starfsviðtal
Uppfært |
Júlí 2, 2015
|
Höfundur | powershell-guru.com |
Grunnur | icelandic.powershell-guru.com |
Flokkar |
75
|
Spurningar |
610
|
System
Hvernig veit ég hvaða útgáfu af PowerShell ég er með?
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 } |
Hvernig á að keyra PowerShell í annarri útgáfu fyrir afturvirka sanhæfni?
powershell.exe -Version 2.0
Hvernig á að krefjast lágmarks PowerShell útgáfa (3.0 og hærri) í skriftu með Powershell? ?
#Requires -Version 3.0
Hvernig á að byðja um rótarheimild fyrir skriftu með PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Hvernig á að athuga breytur í PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Hvernig á að fá upplýsingar um núverandi notanda með PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Hvernig á að búa til, breyta og endurhlaða sniði 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 |
Hvernig á að gera hlé í 5 sekúndur / mínútur í skriftu með PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Hvernig á að fá síðastur ræsingu með PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Hvernig á að fá accelerators 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 |
Hvernig á að fá upp lista yfir startup forrit með PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Hvernig á að fjarlægja forrit með PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Hvernig á að taka screenshot af öllu skrifborði eða virkum glugga með PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Hvernig á að fá upplýsingar um fjölda skilaboða sem bíða í MSMQ með PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Hvernig á að stilla framkvæmd stefnu 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 |
Hvernig á að tvöfalda 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() |
Hvernig á að afpinna eða losa forrit úr taskbar 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') |
Hvernig á að opna Windows Explorer með PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Hvernig á að skrá rekill með PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Hvernig á að búa til 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') |
Hvernig á að fá upplýsingar um staðsetningu tímabundinnar skrár fyrir the núverandi notanda með PowerShell?
[System.IO.Path]::GetTempPath()
Hvernig á að taka þátt í slóð og undirslóð með PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Hvernig á að skrá allar cmdlets “Get- *” með PowerShell?
Get-Command -Verb Get
Hvernig á að skrá sérstakar kerfismöppur með PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Hvernig á að tengja ISO / VHD skrá við PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Hvernig á að athuga hvaða NET Framework útgáfa er uppsett 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 |
Hvernig á að athuga hvort NET Framework útgáfa 4.5 er uppsett með PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Hvernig á að byrja og hætta afrit (til að búa til skrá yfir Windows PowerShell vinnslu ) með PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Hvernig á að færa núverandi möppu á sérstakan stað með PowerShell?
Set-Location -Path 'C:\scripts'
Hvernig á að hreinsa skjáinn með PowerShell?
Clear-Host
cls # Alias
Hvernig á að breyta skjáupplausn með PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Hvernig á að stilla “full screen” glugga með PowerShell?
mode.com 300
Hvernig á að fá mál (breidd og hæð) á mynd 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 } |
Hvernig á að fá Windows vöru lykill 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
Hvernig á að fá núverandi (meðaltal) “% örgjörva tíma” síðustu 5 sekúndur (10 sinnum) með PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Hvernig á að hlaða Smalamáli 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') |
Hvernig á að athuga núverandi NET Smalamál 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*' } |
Hvernig á að finna GAG (Global Assembly Cache) slóð 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
Hvernig á að afrita niðurstöður á klemmuspjald með PowerShell?
1 |
Get-Process | clip.exe |
Hvernig á að fá upp efni á klemmuspjaldi með PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Hvernig á að fá hotfixes uppsett með PowerShell?
Get-HotFix -ComputerName $computer
Hvernig á að fá hotfixes uppsett áður / eftir ákveðna dagsetningu 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
Hvernig á að athuga hvort Hotfixi er uppsett með PowerShell?
Get-HotFix -Id KB2965142
Hvernig á að fá hotfixes uppsett í annari tölvu með PowerShell?
Get-HotFix -ComputerName $computer
Pagefile
Hvernig á að fá Pagefile upplýsingar með PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Hvernig á að fá ráðlagðn stærð (MB) fyrir Pagefile með PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Hvernig á að búa til Pagefile (4096 MB) á (D drifi með PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Hvernig á að eyða Pagefile á (C drif 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
Hvernig á að athuga fragmentation drifs með PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Hvernig á að athuga pláss á diski 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
Hvernig á að opna skrá með PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Hvernig á að lesa skrá með PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Hvernig á að fá output skráar með PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
Hvernig á að fá fullt nafn núverandi skriftu skráar með PowerShell?
$MyInvocation.MyCommand.Path
Hvernig til að þjappa / zip skrám með PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
Hvernig á að afþjappa /þjappa skrám með PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
Hvernig á að sjá skrár í ZIP skjalasafn með PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Hvernig á að sýna stærð skráar í KB með PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Hvernig á að finna skrár stærri eða minni en 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} |
Hvernig á að birta nafnið á skránni án framlengingar með PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Hvernig á að birta framlengingu skráar með PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Hvernig á að fá skráar útgáfu af skrá með PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Hvernig á að fá hash af skrá með PowerShell?
(Get-FileHash $file).Hash
Hvernig á að fá MD5 / SHA1 af skrá með PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Hvernig á að sýna faldar skrár 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 |
Hvernig á að athuga hvort skráin hefur framlengingu með PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Hvernig á að setja upp skrá sem “Read Only” með PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Hvernig á að breyta “LastWriteTime” til síðustu viku á skrá með PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Hvernig á að búa til nýja skrá með PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Hvernig á að endurnefna skrá með PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Hvernig á að endurnefna margar skrár með PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Hvernig á að eyða skrá með PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
Hvernig á að birta 10 síðustu línur skrá með PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Hvernig á að opna margar skrár úr möppu með PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Hvernig á að fjarlægja tómar línur úr skrá með PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Hvernig á að athuga hvort skráin er til með PowerShell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Hvernig á að fá nýjustu / elstu skránna sem hefur verið búin til möppu 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 |
Hvernig á að fjarlægja afritaðar línur úr skrá 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 |
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 |
Hvernig á að fá skrá búna til fyrir meira eða minna en 1 ári í möppu 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 |
Hvernig á að flytja verðmæti breytu til skrá með PowerShell?
Set-Content -Path file.txt -Value $variable
Hvernig á að telja fjölda skráa (* .txt) í möppu 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 |
Hvernig á að leita af strengi innan um margar skrár með PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Hvernig á að birta fyrstu / síðustu línu skráar 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 |
Hvernig á að sýna sérstaka línu fjölda skráa 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 |
Hvernig á að telja fjölda lína skráar með PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Hvernig á að telja fjölda stafa og orða skráar 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 |
Hvernig á að sækja skrá með PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Hvernig á að birta fulla slóð skráar með PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Hvernig á að afrita eina skrá í möppu með PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Hvernig á að afrita eina skrá úr mörtgum möppum með PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Hvernig á að afrita margar skrár í einni möppu með PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Hvernig á að finna Global Catalog Server í Active Directory með PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Hvernig á að finna síður í Active Directory með PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Hvernig á að finna núverandi léns stjórnanda með PowerShell?
(Get-ADDomainController).HostName
Hvernig á að finna allar ríki stýringar í léni 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} |
Hvernig á að finna AD afritunar mistök með PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
Hvernig á að finna Tombstone endingartíma fyrir skóg í Active Directory með PowerShell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Hvernig á að fá upplýsingar um skóginn / lénið í Active Directory með PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Hvernig á að fá slóð á “Eyddum hlutum” í gám í Active Directory með PowerShell?
(Get-ADDomain).DeletedObjectsContainer
Hvernig á að gera AD Recycle Bin lögun í Active Directory 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' |
Hvernig á að endurheimta AD reikning úr ruslafötunni í Active Directory með PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Hvernig á að finna FSMO hlutverk 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 |
Hvernig á að tengja við tiltekið lén stjórnanda með PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'
Hvernig á að fá núverandi innskráningar miðlara með PowerShell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Hvernig á að framkvæma “gpupdate” á tölvu með PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Hvernig á að búa til nýjan hóp í Active Directory 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' |
Hvernig á að fjarlægja hóp í Active Directory með PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'
Hvernig á að bæta notanda við hóp í Active Directory með PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Hvernig á að fjarlægja notanda úr hópi í Active Directory með PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Hvernig á að finna tóma hópa (með engum meðlimi) í Active Directory með PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Hvernig á að telja tóma hópa (með engum meðlimi) í Active Directory með PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Hvernig á að fá meðlimi hóps í Active Directory 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' |
Hvernig á að fá meðlimi hóps með endurkvæma meðlimum í Active Directory 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
Hvernig á að nota algildisstaf í síu “Fá-ADUser” í Active Directory með PowerShell?
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
Hvernig á að færa notanda til annars OU í Active Directory með PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Hvernig á að finna alla meðlimi sem eru (hreiðraðir) til notandi með PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Hvernig á að gefa meðlimum (stuttnefni / styttu) fyrir notandi 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 |
Hvernig á að breyta lýsingu, vinnustað og símanúmeri notanda í Active Directory 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 |
Hvernig á að opna notenda reikning í Active Directory með PowerShell?
Unlock-ADAccount $samAccountName
Hvernig á að gera notanda reikningur í Active Directory með PowerShell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Hvernig á að fjarlægja notanda í Active Directory með PowerShell?
Remove-ADUser $samAccountName
Hvernig á að endurstilla lykilorð fyrir einn notanda í Active Directory 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 |
Hvernig á að finna eiganda af skrá í Active Directory 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 |
Hvernig á að finna OU (Organizational Unit) fyrir notanda í Active Directory með PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Hvernig á að finna lokaða notendareikninga í Active Directory með PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Hvernig á að finna útrunna notendareikninga í Active Directory með PowerShell?
Search-ADAccount -AccountExpired
Hvernig á að finna læsta notendareikninga í Active Directory með PowerShell?
Search-ADAccount -LockedOut
Hvernig á að finna SID af notanda í Active Directory með PowerShell?
(Get-ADUser $user -Properties SID).SID.Value
Hvernig á að umbreyta notandanafni í SID í Active Directory með PowerShell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Hvernig á að umbreyta SID notandanafni í Active Directory með PowerShell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
Hvernig á að skipta Distinguished Name af notanda í Active Directory 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" |
Hvernig á að finna dagsetningu sköpun / breytingar á notanda í Active Directory 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 |
Hvernig á að fá LDAP leið fyrir notanda í Active Directory 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 |
Hvernig á að breyta CN (Canonical Name) fyrir notanda í Active Directory með PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Hvernig á að fá Organizational Unit (OU) foreldri notanda Active Directory með PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
Hvernig á að fá eiganda notanda (sem bjó til reikning) í Active Directory með PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Hvernig á að umbreyta PwdLastSet eigindi fyrir notanda í Active Directory með PowerShell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Hvernig á að prófa örugga rás milli heimatölvu og léns með PowerShell?
Test-ComputerSecureChannel
Hvernig á að gera örugga rás milli the heimatölvu og léns með PowerShell?
Test-ComputerSecureChannel -Repair
Hvernig á að slökkva á tölvu reikningi í Active Directory með PowerShell?
Disable-ADAccount $computer
Hvernig á að finna tölvur með tilteknum stýrikerfum í Active Directory 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)
Hvernig á að búa til Organizational Unit (OU) í Active Directory með PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Hvernig á að fá Organizational Unit (OU) upplýsingar í Active Directory með PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Hvernig á að breyta lýsingu á Organizational Unit (OU) í Active Directory með PowerShell?
Set-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Description 'My description'
Hvernig á að gera Organizational Unit (OU) frá slys eyðingu í Active Directory með PowerShell?
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 |
Hvernig á að skrá tóma skipulag einingar (alvarlegar) 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 } |
Hvernig á að fá upp stjórnanda hóp með PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Hvernig á að draga IP tölu V4 (80.80.228.8) með Regex léni 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
Hvernig á að draga a MAC tölu (C0-D9-62-39-61-2D) með skilju “-” með Regex léni 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
Hvernig á að draga a MAC tölu (C0: D9: 62: 39: 61: 2D) með skilju “:” 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
Hvernig á að draga dagsetningu (2015/10/02) með Regex léni með PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Hvernig á að draga a 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
Hvernig á að draga tölvupóst (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
Hvernig á að draga “sérfræðingur” frá bandi td með Regex með PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Hvernig á að draga “guru.com” frá bandi td með Regex með PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Hvernig á að draga “powershell-guru.com” frá bandi td með Regex með PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Hvernig á að draga “123” frá bandi td með Regex með PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Hvernig á að draga “$” (dollaramerki) frá strengnum td með Regex með PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Hvernig á að skipta um persónu (* .com) með annað (* .fr) í streng með Regex með PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Hvernig á að flýja a band með Regex með PowerShell?
[regex]::Escape('\\server\share')
Memory
Hvernig á að þvinga minnissöfnun með sorp safnara með PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Hvernig á að fá upp RAM stærð tölvu 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
Hvernig á að fá núverandi dagsetningi með PowerShell?
Get-Date
[Datetime]::Now
Hvernig á að sýna dagsetninguna í mismunandi sniðum 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 |
Hvernig á að umbreyta dagsetningu (datetime) að degi (String) með PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
Hvernig á að umbreyta dagsetningu (String) að degi (datetime) með PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
Hvernig á að reikna mismuninn (fjöldi daga, klukkustunda, mínútuna, eða sekúndna) á milli tveggja dagsetninga 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
Hvernig á að bera saman tvær dagsetningar 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
Hvernig á að raða á fjölbreyttum dagsetningaum sem “datetime” með PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Hvernig á að byrja og enda skeiðklukku með PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Hvernig á að fá núverandi viku með PowerShell?
(Get-Date).DayOfWeek #Sunday
Hvernig á að fá dagsetningu í gær með PowerShell?
(Get-Date).AddDays(-1)
Hvernig á að fá fjölda daga í mánuði (í febrúar 2015) með PowerShell?
[DateTime]::DaysInMonth(2015, 2)
Hvernig á að vita hlaupár með PowerShell?
[DateTime]::IsLeapYear(2015)
Hvernig á að skrá tímabelti með PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Hvernig á að umrita (til ASCII sniðs) og lesa vefslóð 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 |
Hvað eru jafngildi af móðurmáli net stjórnar 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 |
Hvernig á að fá IP-tölu með PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Hvernig á að slökkva á IP tölu V6 (IPv6) með PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Hvernig á að sannreyna IP tölu V4 (IPv4) með PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}
Hvernig á að finna ytri IP tölu 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 } |
Hvernig á að finna vélarheiti frá IP-tölu með PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Hvernig á að finna IP tölu frá vélarheiti með PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Hvernig á að finna FQDN frá vélarheiti með PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
Hvernig á að finna net stillingar (Ip, subnet, Gateway og DNS) með PowerShell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Hvernig á að finna MAC-tölu með PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Hvernig á að smellur tölvu 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) |
Hvernig á að athuga hvort tölvan er tengd við internetið með PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Hvernig á að framkvæma “Whois” athugun vefsíðu með PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Hvernig á að fá upplýsingar um opinbera IP (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 |
Hvernig á að athuga hvort höfn er opinn / lokuð með PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Hvernig á að framkvæma “tracert” með PowerShell?
Test-NetConnection www.google.com -TraceRoute
Hvernig á að festa net tengingu upplýsingar með PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Hvernig á að sýna TCP hafnar tengsl við PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Hvernig á að stytta langa vefslóð í litla vefslóð með PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Hvernig á að fá umboð stillingar með PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Hvernig á að athuga DNS skyndiminni á þinni tölvu með PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Hvernig á að hreinsa DNS skyndiminni á þinni tölvu með PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Hvernig á að hreinsa DNS skyndiminni á fjarlægum tölvum með PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Hvernig á að lesa Gestgjafi skrá með PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Hvernig á að búa til lykilorð af handahófi með PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Hvernig á að breyta staðartíma lykilorði fyrir stjórnanda á ytri miðlara með PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Hvernig á að finna lykilorð gildistíma reiknings í Active Directory 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
Hvernig á að skrá alla prentara fyrir tiltekin netþjón með PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Hvernig á að skrá alla þá tengi fyrir ákveðna miðlara með PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Hvernig á að breyta athugasemd / staðsetningu á prentara 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() |
Hvernig á að hreinsa (hætta öllum störfum) í prentara með PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Hvernig á að prenta út próf síðu fyrir prentara með PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Hvernig á að fá prentbiðraðir fyrir prentara 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
Hvernig á að skrá skrásetningu hives með PowerShell?
Get-ChildItem -Path Registry::
Hvernig á að fá gildi skrásetninga oggerð gilda 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) } } } |
Hvernig á að skrá skrásetningu lykils undirlykla 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:\' |
Hvernig á að skrá skrásetningu lykils undirlykla á endurkvæmam hátt með PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Hvernig á að finna undirlykla með tiltekið nafn með PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Hvernig á að skila aðeins nafni af skrásetningu undirlykla með PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Hvernig á að skrá skrásetningu gildis með PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Hvernig á að lesa ákveðna skrásetningu gildis með PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Hvernig á að lesa ákveðna skrásetning gildi á fjarlægri tölvu 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
Hvernig á að búa til nýjan skrásetningar lykill með PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'
Hvernig á að búa til skrásetningar gildi með PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Hvernig á að breyta núverandi skrásetningar gildi með PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Hvernig á að eyða skrásetningar gildi með PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Hvernig á að eyða skrásetningar lykil með PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Hvernig á að prófa ef skrásetningar lykil til með PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'
Hvernig á að prófa ef skrásetningar gildi til með PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Hvernig á að fjarlægja hvíta-rúm stafi frá upphafi strengs með PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Hvernig á að fjarlægja hvíta-rúm stafi frá lokuðu bandi með PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Hvernig á að fjarlægja hvíta-rúm stafi (upphaf og endir) á streng með PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()
Hvernig á að umbreyta bandi í hástafi með PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()
Hvernig á að umbreyta bandi til að lækka tilfelli með PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Hvernig á að velja undirstreng “PowerShell” á bandi “PowerShellGuru” með PowerShell?
$string.Substring(0,10)
Hvernig á að velja hlutstreng “Guru” á bandi “PowerShellGuru” með PowerShell?
$string.Substring(10)
Hvernig á að velja “123” af “PowerShell123Guru” með PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Hvernig á að fá núll-undirstöðu vísitölu “Guru” í band “PowerShellGuru” með PowerShell?
$string.IndexOf('Guru') # 10
Hvernig á að athuga hvort strengurinn er núll eða auður með PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Hvernig á að athuga hvort strengurinn er núll, tómur, eða samanstendur aðeins af hvíta-rúms stöfum með PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Hvernig á að athuga hvort strengurinn inniheldur ákveðna stafi með PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Hvernig á að skila lengd strengs með PowerShell?
$string.Length
Hvernig til sameina tvo strengi með PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Hvernig á að passa fyrir einn eða fleiri sviga “[]” í streng með PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Hvernig á að passa fyrir einn eða fleiri sviga “()” í streng með PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Hvernig á að passa fyrir einn eða fleiri hrokkið sviga “{}” í streng með PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Hvernig á að passa fyrir eitt eða fleiri sviga horn “<>” í streng með PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Hvernig á að passa alla lágstafi (ABC) í streng með PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Hvernig á að passa alla hástafi (ABC) í streng með PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Hvernig á að passa “[bls” (p lágstöfum) í streng með PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Hvernig á að passa “[P” (P hástaf) í streng með PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Hvernig á að skipta línu út fyrir aðra línu með PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Hvernig á að breyta deildri aðgerð í streng (prósentu) með PowerShell?
(1/2).ToString('P')
Hvernig á að raða strengjum sem innihalda tölur með PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Hvernig á að velja síðasta orð í setningu með PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Hvernig á að fá lengsta orð í setningu með PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Hvernig á að telja fjölda skiptum strengjum sem eru til staðar innan setningu með PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Hvernig á að afrita hvern staf í streng að bókstaf fylki með PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Hvernig á að umbreyta fyrsta stafi í hástafi af streng með PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Hvernig á að púða (vinstri eða hægri) a band 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 |
Hvernig á að umrita og lesa streng til 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 |
Hvernig á að breyta fjölda (til og frá) tvöfalds 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) |
Hvernig á að skila aðeins síðastu yfirmöppu í leið með PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Hvernig á að skila aðeins síðasta atriði í leið með PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Hvernig á að skrá aðferðir við System.Math bekknum með PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
Hvernig á að skila algildi með PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Hvernig á að skila horn hvers sínus er tiltekinn fjöldi með PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
Hvernig á að skila loft gildi með PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Hvernig á að skila gólf gildi með PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Hvernig á að skila náttúrulegum (stöð e) logra af tilteknum fjöldi með PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
Hvernig á að skila stöð 10 logra af tiltekinum fjölda með PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
Hvernig á að skila allt að tveimur gildum með PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Hvernig á að skila amk tveim gildum með PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Hvernig á að skila fjölda hækkana í tilteknu afli með PowerShell?
[Math]::Pow(2,4) #Returns 16
Hvernig á að skila aukastaf gildis til næsta órofa gildis með PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Hvernig á að skila óaðskiljanlegum hlut tiltekinnar heiltölu með PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Hvernig á að skila ferningsrót af tilteknum fjölda með PowerShell?
[Math]::Sqrt(16) #Returns 4
Hvernig á að skila PI stöðu með PowerShell?
[Math]::Pi #Returns 3,14159265358979
Hvernig á að skila náttúrulegri lógaritma stöð (fasti e) með PowerShell?
[Math]::E #Returns 2,71828182845905
Hvernig á að athuga hvort tala er jafnvel eða stök með PowerShell?
[bool]($number%2)
Hashtables
Hvernig á að búa til tóma Hashtable með PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Hvernig á að búa til Hashtable með atriði 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 |
Hvernig á að bæta hlutum (lykill-gildi par) til Hashtable með PowerShell?
$hashtable.Add('Key3', 'Value3')
Hvernig til fá a sérstakt verðmæti Hashtable með PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Hvernig á að fá lágmarks verðmæti Hashtable 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 |
Hvernig á að fá hámarks verðmæti Hashtable 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 |
Hvernig á að breyta atriði í Hashtable með PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Hvernig á að fjarlægja atriði í Hashtable með PowerShell?
$hashtable.Remove('Key1')
Hvernig á að hreinsa Hashtable með PowerShell?
$hashtable.Clear()
Hvernig á að athuga tilvist ákveðinna takka / gilda í Hashtable með PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Hvernig á að raða eftir takka / gildum í Hashtable með PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Hvernig á að búa til tómt fylki með PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()
Hvernig á að búa til fylki með atriði 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
Hvernig á að bæta hlutum við fylki með PowerShell?
$array += 'D'
[void]$array.Add('D')
Hvernig á að breyta hlut í fylki með PowerShell?
$array[0] = 'Z' # 1st item[0]
Hvernig á að athuga stærð fylkis með PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Hvernig á að sækja eitt atriði / nokkur / öll atriði í fylki 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)
Hvernig á að fjarlægja tóm atriði í fylki með PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Hvernig á að athuga hvort atriði er fyrir hendi í fylki með PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Hvernig á að finna vísitölu fjölda hluta í fylki með PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Hvernig á að snúa röð liða í fylki með PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Hvernig á að búa til handahófskennt atriði úr fylki með PowerShell?
$array | Get-Random
Hvernig á að raða fylki á vaxandi / lækkandi máta með PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Hvernig á að telja fjölda hluta í fylki með PowerShell?
$array.Count
Hvernig á að bæta við fjölda til annars með PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Hvernig á að finna afrit af fjölda með PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
Hvernig á að fjarlægja afrit úr fjölda með PowerShell?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
Hvernig á að búa til fylki með atriðum sem byrja með forskeyti (“user01″, “user02″, … “user10″) með PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Hvernig á að skrá ACL af AD notenda með PowerShell?
(Get-Acl -Path "AD:\$dn").Access
Hvernig á að skrá ACL af möppu með PowerShell?
(Get-Acl -Path C:\scripts).Access
Hvernig á að skrá tilteknar ACL leyfðar færslur (eða -hópa) af AD notandi með PowerShell?
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
Hvað eru algengustu gagnagildi með 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 |
Hvernig á að finna lágmarks og hámarks gildi fyrir sumar tegundur breytna 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 |
Hvernig á að prófa datatype með PowerShell?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
Hvernig á að búa til hér-streng breytu með 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} "@ |
Hvernig á að búa til breytu með PowerShell?
$powershellGuru = 'Hello'
Hvernig á að búa til stöðuga breytu með PowerShell?
Set-Variable -Name powershellGuru -Value 2015 -Option Constant
Hvernig á að búa til alþjóðlega breytu með PowerShell?
$Global:powershellGuru = 'Hello'
Hvernig á að lesa breytu með PowerShell?
$powershellGuru = 'Hello' # Create
$powershellGuru # Read
Get-Variable -Name powershellGuru -ValueOnly # Read
Hvernig á að athuga hvaða breyta er í notkun með PowerShell?
$powershellGuru.GetType()
Hvernig á að finna breytur með alþjóðlegu umfangi með PowerShell?
Get-Variable -Scope Global
Hvernig á að sýna ákveðinar breytur eftir nafni með PowerShell?
Get-Variable -Include *Preference -Exclude W*
Hvernig á að tengja sérstaka gagnagerð breytu með PowerShell?
[int64]$variable = 100
[string]$variable = 'PowershellGuru'
Hvernig á að frumstilla margar breytur í sama gildi með PowerShell?
$a = $b = $c = $d = $e = 0
Hvað er samnefni fyrir breytuna “$ _” með PowerShell?
Get-Process | Where-Object -FilterScript {$_.Handles -gt 1000} # Using $_
Get-Process | Where-Object -FilterScript {$PSItem.Handles -gt 1000} # Using $PSItem (since version 3)
Hvernig á að fjarlægja breytur með nafni sem hefst með “telja” með PowerShell?
Remove-Variable -Name count*
Hvernig á að fá staðbundið breytuumhverfi með PowerShell?
Get-ChildItem -Path Env:
Hvernig á að fá slóðina Environmental Variable línu fyrir línu með PowerShell?
($env:Path) -replace(';', "`n")
[Environment]::GetEnvironmentVariable('Path') -replace(';', "`n")
Hvernig á að bæta við nýjum slóðum (ex C:. \ SysinternalsSuite) til Path Umhverfis breytu með PowerShell?
$env:Path += ';C:\SysinternalsSuite'
$env:Path = $env:Path + ';C:\SysinternalsSuite'
Hvernig á að samræma breytur með PowerShell?
$a = 'Powershell'
$b = '- Guru'
$c = $a + $b
Hvernig á að nota ErrorVariable með PowerShell?
Get-ChildItem -Path 'C:\PerfLogs' -ErrorAction SilentlyContinue -ErrorVariable AccessDenied
$AccessDenied | ForEach-Object -Process {$_.Exception}
$AccessDenied | ForEach-Object -Process {$_.TargetObject}
1 2 3 4 5 6 7 |
#Enable Set-PSDebug -Strict $a #The variable '$a' cannot be retrieved because it has not been set. # Disable Set-PSDebug -Off $a #No error displayed |
Static .NET Methods
Hvernig á að fá truflanir meðlimna með PowerShell?
[DateTime] | Get-Member -Static
Sounds
Hvernig á að spila “píp” hljóð með PowerShell?
[System.Console]::Beep()
Hvernig á að spila “Asterisk” hljóð með PowerShell?
[System.Media.SystemSounds]::Asterisk.Play()
Hvernig á að spila “upphrópunarmerki” hljóð með PowerShell?
[System.Media.SystemSounds]::Exclamation.Play()
Hvernig á að fá tiltækt hljóð með PowerShell?
[System.Media.SystemSounds] | Get-Member -Static
Hvernig á að spila “WAV” hljómar með PowerShell?
$soundPlayer = New-Object -TypeName System.Media.SoundPlayer -ArgumentList "$env:windir\Media\Ringout.wav"
$soundPlayer.Play()
eða
$soundPlayer.PlayLooping()
$soundPlayer.Stop()
Hvernig á að virkja ræðu texta með PowerShell?
Add-Type -AssemblyName System.Speech
$speech = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$speech.Speak('Hello PowershellGuru')
XML
Hvernig á að lesa XML skrá með PowerShell?
[xml]$sitemap = Get-Content -Path .\sitemap.xml
$sitemap.urlset.url
Hvernig á að flytja gögn eins og XML skrá með PowerShell?
Get-Process | Export-Clixml -Path C:\scripts\processes.xml
Hvernig á að flytja gögn úr CLIXML skrá með PowerShell?
$importProcesses = Import-Clixml -Path C:\scripts\processes.xml
GUI
Hvernig á að búa til grunn GUI (Windows Form) með PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 |
Add-Type -AssemblyName System.Windows.Forms $form = New-Object -TypeName system.Windows.Forms.Form $label = New-Object -TypeName System.Windows.Forms.Label $label.Text = 'PowershellGuru' $label.AutoSize = $true $label.Location = New-Object -TypeName Drawing.Point -ArgumentList 5, 10 $button = New-Object -TypeName Windows.Forms.Button $button.Text = 'OK' $button.Location = New-Object -TypeName Drawing.Point -ArgumentList 5, 30 $form.Controls.Add($label) $form.Controls.Add($button) $form.ShowDialog() |
Characters
Hvernig á að breyta ASCII gildi til persónu með PowerShell?
[char]64
Hvernig á að breyta staf ASCII gildis með PowerShell?
[int][char]'@'
Hvernig á að búa til enska stafrófið með PowerShell?
[char[]](97..122)
Compare
Hvernig á að bera saman tvö fylki með PowerShell?
1 2 3 4 5 |
$a = @(1, 2, 3) $b = @(2, 3) Compare-Object -ReferenceObject $a -DifferenceObject $b -IncludeEqual | Where-Object -FilterScript {$_.SideIndicator -eq '<='} # Returns 1 Compare-Object -ReferenceObject $a -DifferenceObject $b -IncludeEqual | Where-Object -FilterScript {$_.SideIndicator -ne '=='} # Returns 1 Compare-Object -ReferenceObject $a -DifferenceObject $b -IncludeEqual | Where-Object -FilterScript {$_.SideIndicator -eq '=='} # Returns 2 and 3 |
Hvernig á að bera saman tvö ferli með PowerShell?
1 2 3 |
$process1 = Get-Process -Id 8248 $process2 = Get-Process -Id 376 Compare-Object -ReferenceObject $process1 -DifferenceObject $process2 -Property Handles, NPM, PM, WS, VM, CPU |
Microsoft Exchange
Hvernig á að sækja lista yfir farsíma samstilltan við pósthólf notenda með PowerShell?
Get-ActiveSyncDeviceStatistics
Hvernig á að bæta við “Full Access” heimildimu við pósthólf notanda með PowerShell?
Add-MailboxPermission -Identity $dn -User 'DOMAIN\powershellguru' -AccessRights 'FullAccess'
Hvernig á að fjarlægja “Full Access” heimild að pósthólfi notanda með PowerShell?
Remove-MailboxPermission -Identity $dn -User 'DOMAIN\powershellguru' -AccessRights 'FullAccess' -InheritanceType 'All'
Hvernig á að bæta við “Senda sem” heimild til pósthólf notandi með PowerShell?
Add-ADPermission -Identity $dn -User 'DOMAIN\powershellguru' -ExtendedRights 'Send-As'
Hvernig á að fjarlægja “Senda sem” leyfi til pósthólfs notanda með PowerShell?
1 |
Remove-ADPermission -Identity $dn -User 'DOMAIN\powershellguru' -ExtendedRights 'Send-As' -InheritanceType 'All' -ChildObjectTypes $null -InheritedObjectTypes $null -Properties $null |
Hvernig á að finna Innhólf reglur pósthólfs með PowerShell?
Get-InboxRule -Mailbox 'Powershell.Guru'
Hvernig á að fá SMTP-vistfang notendenda sem hafa OWA (Outlook Web Access) virkt með PowerShell?
Get-CASMailbox -Filter{OWAEnabled -eq $true} | Select-Object -Property Name, PrimarySMTPAddress
Exchange 2007
1 2 |
ServerManagerCmd -i RSAT-ADDS ServerManagerCmd -i PowerShell Web-Server Web-ISAPI-Ext Web-Metabase Web-Lgcy-Mgmt-Console Web-Basic-Auth Web-Digest-Auth Web-Windows-Auth Web-Dyn-Compression RPC-over-HTTP-proxy |
Exchange 2010
1 2 3 |
Import-Module -Name ServerManager Add-WindowsFeature NET-Framework, RSAT-ADDS, Web-Server, Web-Basic-Auth, Web-Windows-Auth, Web-Metabase, Web-Net-Ext, Web-Lgcy-Mgmt-Console, WAS-Process-Model, RSAT-Web-Server, Web-ISAPI-Ext, Web-Digest-Auth, Web-Dyn-Compression, NET-HTTP-Activation, RPC- Over-HTTP-Proxy -Restart |
Exchange 2013