Kunċett : L-aktar mistoqsijiet frekwenti dwar Powershell.
Tista ‘tuża din il-lista b’modi differenti :
- Li kopja / paste jikkmanda fis iskrittura
- Biex tara malajr l-sintassi ta ‘kmand speċifiku
- Biex itejbu l-għarfien tekniku tiegħek
- Biex jiskopru ordnijiet ġodda
- Biex tipprepara intervista tax-xogħol
Aġġornata |
2 Lulju, 2015
|
Awtur | powershell-guru.com |
Sors | maltese.powershell-guru.com |
Kategoriji |
75
|
Mistoqsijiet |
610
|
System
Kif ikun determinat verżjoni tiegħi ta ‘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 } |
Kif jitmexxa PowerShell fil-verżjoni ieħor għal kompatibilità b’lura?
powershell.exe -Version 2.0
Kif jeħtieġu verżjoni PowerShell minimu (3.0 u ogħla) fi b’kitba ma PowerShell?
#Requires -Version 3.0
Kif jeħtieġu privileġġi amministrattivi għal b’kitba bl PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
Kif jikkontrollaw il-parametri ta ‘iskrittura ma PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
Kif tikseb l-informazzjoni għall-utent attwali ma PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
Kif toħloq, teditja, u rikarigu profil ma ‘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 |
Kif jagħmlu waqfa ta ‘5 sekondi / minuta b’kitba ma PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
Kif tikseb l-aħħar darba boot mal PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
Kif tikseb aċċeleraturi tip ma 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 |
Kif jiġu elenkati l-programmi l-istartjar bil PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
Kif uninstall applikazzjoni ma PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
Kif għandek tieħu screenshot ta ‘l-desktop kollu jew ta’ tieqa attiva ma PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
Kif tikseb l-għadd messaġġ għall-kjuwijiet MSMQ ma PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
Kif jiġu stabbiliti l-politika ta ‘eżekuzzjoni ma 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 |
Kif tinħoloq shortcut ma 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() |
Kif biex jagħrfu jew unpin programm għall-taskbar ma 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') |
Kif tiftaħ Windows Explorer mal PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
Kif telenka sewwieqa apparat ma PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
Kif tinħoloq GUID ma 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') |
Kif tikseb l-post tad-direttorju temporanju għall-utent attwali ma PowerShell?
[System.IO.Path]::GetTempPath()
Kif tissieħeb triq u triq f’wieħed passaġġ wieħed minuri ma PowerShell?
Join-Path -Path C:\ -ChildPath \windows
Kif għall-lista cmdlets kollha “Get- *” ma PowerShell?
Get-Command -Verb Get
Kif telenka folders sistema speċjali ma PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
Kif impunjazzjoni ISO fajls / VHD ma PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
Kif biex jiċċekkjaw verżjonijiet Qafas NET installati mal 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 |
Kif biex jiċċekkjaw jekk il-verżjoni Qafas NET 4.5 huwa installat ma ‘PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
Kif tibda u tieqaf traskrizzjoni (li jinħoloq rekord tas-sessjoni Windows PowerShell) ma PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
Kif tibdel l-direttorju kurrenti għal lokazzjoni speċifika ma PowerShell?
Set-Location -Path 'C:\scripts'
Kif ċar l-iskrin bl PowerShell?
Clear-Host
cls # Alias
Kif tibdel l-riżoluzzjoni tal-wirja bl PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
Kif jiġu stabbiliti l-“full screen” tieqa bil PowerShell?
mode.com 300
Kif tikseb dimensjonijiet (wisa ‘u għoli) ta’ stampa mal 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 } |
Kif tikseb l-prodott ewlieni Windows PowerShell ma?
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
Kif tikseb l-kurrent “Time% Processor” (medja) fl-aħħar 5 sekondi (10 darbiet) ma PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
Kif tagħbija assemblaġġi 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') |
Kif biex jiċċekkjaw assemblaġġi NET attwali mgħobbija bil 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*' } |
Kif issib l-GAC (Assemblea Global Cache) passaġġ bl PowerShell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
Kif kopja riżultati lill-clipboard ma PowerShell?
1 |
Get-Process | clip.exe |
Kif tikseb l-kontenut tal-clipboard ma PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
Kif tikseb l-hotfixes installati mal PowerShell?
Get-HotFix -ComputerName $computer
Kif tikseb l-hotfixes installati qabel / wara data speċifika ma 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
Kif biex jiċċekkjaw jekk hotfix huwa installat ma ‘PowerShell?
Get-HotFix -Id KB2965142
Kif tikseb l-hotfixes installat fuq kompjuter remot bl PowerShell?
Get-HotFix -ComputerName $computer
Pagefile
Kif tikseb informazzjoni pagefile ma PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
Kif tikseb l-daqs rakkomandat (MB) għall-pagefile ma PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
Kif tinħoloq pagefile (4096 MB) dwar il- (D 🙂 issuq bil PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
Kif tħassar pagefile dwar il- (C 🙂 drive ma 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
Kif biex jiċċekkja l-frammentazzjoni ta ‘drive ma PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
Kif biex jiċċekkja l-ispazju disk drives ta ‘mal 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
Kif tiftaħ fajl ma PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
Kif jaqraw fajl ma PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
Kif jiktbu output għall-fajl ma PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
Kif tikseb l-fullname tal-fajl iskrittura attwali PowerShell?
$MyInvocation.MyCommand.Path
Kif jikkompressa / fajls zip mal PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
Kif uncompress / fajls unzip ma PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
Kif tara l-fajls fil arkivju code bil PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
Kif juru d-daqs ta ‘fajl fi KB mal PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
Kif issib fajls akbar jew inqas minn 1 GB ma 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} |
Kif turi l-isem ta ‘fajl mingħajr estensjoni ma PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
Kif juru l-estensjoni ta ‘fajl ma PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
Kif tikseb l-verżjoni fajl ta ‘fajl ma PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
Kif tikseb l-hash tal-fajl ma PowerShell?
(Get-FileHash $file).Hash
Kif tikseb l-checksum MD5 / SHA1 ta ‘fajl ma PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
Kif juru fajls moħbija ma PowerShell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
Kif biex jiċċekkjaw jekk fajl għandu estensjoni PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
Kif jiffissaw fajl bħala “Aqra biss” ma PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
Kif il-bidla l-“LastWriteTime” attribut li għaddiet ġimgħa għal fajl ma PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
Kif tinħoloq fajl ġdid ma PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
Kif li tibdel isem fajl ma PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
Kif tibdel isem ingrossa / tal-lott fajls multipli ma ‘PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
Kif tħassar fajl ma PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
Kif juru l-aħħar 10 linji ta ‘fajl ma PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
Kif tiżblokka diversi fajls ta ‘folder mal PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
Kif tneħħi linji vojta minn fajl bl PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
Kif biex jiċċekkjaw jekk teżisti fajl ma PowerShell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
Kif tikseb l-aktar ġodda / eqdem fajl maħluqa fil-folder mal 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 |
Kif tneħħi linji duplikat minn fajl bl 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 |
Kif tikseb fajls maħluqin aktar jew inqas minn 1 xahar fil-folder mal 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 |
Kif tikseb fajls maħluqin aktar jew inqas minn 1 sena fil-folder mal 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 |
Kif tesporta l-valur ta ‘varjabbli għall-fajl ma PowerShell?
Set-Content -Path file.txt -Value $variable
Kif jgħodd in-numru ta ‘fajls (* txt) fil-folder mal 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 |
Kif tfittex string ġewwa fajls multipli PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
Kif juru l-ewwel / l-aħħar linja ta ‘fajl ma 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 |
Kif juru numru linja speċifika ta ‘fajl ma 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 |
Kif jgħodd in-numru ta ‘linji ta’ fajl ma PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
Kif jgħodd in-numru ta ‘karattri u kliem ta’ fajl ma 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 |
Kif tniżżel fajl ma PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
Kif juru l-traġitt sħiħ ta ‘fajl ma PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
Kif kopja fajl wieħed għal folder mal PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
Kif kopja fajl wieħed għall folders multipli ma PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
Kif kopja fajls multipli biex folder wieħed ma PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
Kif issib Globali Catalog servers Active Directory ma PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
Kif issib siti fl-Active Directory ma PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
Kif issib l-kontrollur ta ‘domain attwali PowerShell?
(Get-ADDomainController).HostName
Kif issib l-kontrolluri ta ‘domain fi dominju ma 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} |
Kif issib l-fallimenti replikazzjoni AD ma PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
Kif issib l-ħajja tombstone għall-foresti fil-Active Directory ma PowerShell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
Kif tikseb id-dettalji tal-foresta / dominju Active Directory ma PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
Kif tikseb l-passaġġ ta ‘l- “Oġġetti Imħassar” kontenitur fil-Active Directory ma PowerShell?
(Get-ADDomain).DeletedObjectsContainer
Kif tippermetti l-AD karatteristika Recycle Bin fl-Active Directory ma 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' |
Kif biex jirrestawraw Kont AD mill-Recycle Bin fl-Active Directory ma PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
Kif issib l-irwoli FSMO ma 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 |
Kif biex jgħaqqdu ma ‘kontrollur ta’ domain speċifiku ma PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'
Kif tikseb l-server logon attwali PowerShell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
Kif iwettqu “gpupdate” fuq il-kompjuter ma ‘PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
Kif tinħoloq grupp ġdid fil-Active Directory ma 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' |
Kif tneħħi grupp Active Directory ma PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'
Kif żid utent għal grupp fil-Active Directory ma PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
Kif tneħħi utent minn grupp Active Directory ma PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
Kif issib gruppi vojta (bl-ebda membru) fil-Active Directory ma PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
Kif jgħodd gruppi vojta (bl-ebda membru) fil-Active Directory ma PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
Kif tikseb l-membri ta ‘grupp fi Active Directory ma 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' |
Kif tikseb l-membri ta ‘grupp ma’ membri rikursivi fil Active Directory ma 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
Kif għandek tuża Wildcard fil-filtru ta ‘”Get-ADUser” Active Directory ma 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 |
Kif jimxu utent biex OU ieħor Active Directory ma PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
Kif issib l-Membri kollha li huma (nested) għal utent ma PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
Kif tikseb l-Membri (isem qasir / maqtugħ) għal utent ma 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 |
Kif il-bidla l-Deskrizzjoni, Uffiċċju, u n-numru tat-telefown għal kont utent Active Directory ma 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 |
Kif nisfruttaw kont ta ‘utent fil-Active Directory ma PowerShell?
Unlock-ADAccount $samAccountName
Kif tippermetti / jiskonnettja kont ta ‘utent fil-Active Directory ma PowerShell?
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
Kif tneħħi kont ta ‘utent fil-Active Directory ma PowerShell?
Remove-ADUser $samAccountName
Kif reset password għall-kont utent wieħed fil-Active Directory ma 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 |
Kif reset password għal diversi kontijiet utent (bulk) fil Active Directory ma 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 |
Kif issib l-proprjetarju ta ‘fajl fi Active Directory ma 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 |
Kif issib l-OU (unità organizzattiva) għal utent fil-Active Directory ma PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
Kif issib kontijiet utent b’diżabilità fl-Active Directory ma PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
Kif issib kontijiet utent skadew fil Active Directory ma PowerShell?
Search-ADAccount -AccountExpired
Kif issib kontijiet utent maqful fil Active Directory ma PowerShell?
Search-ADAccount -LockedOut
Kif issib l-SID ta ‘kont ta’ utent fil-Active Directory ma PowerShell?
(Get-ADUser $user -Properties SID).SID.Value
Kif jistgħu jikkonvertu username biex SID fl-Active Directory ma PowerShell?
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
Kif jistgħu jikkonvertu l-SID li username fi Active Directory ma PowerShell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
Kif li jaqsam l-Isem Distinti ta ‘kont ta’ utent fil-Active Directory ma 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" |
Kif issib id-data tal-ħolqien / modifika ta ‘kont ta’ utent fil-Active Directory ma 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 |
Kif tikseb l-passaġġ LDAP għal utent fil-Active Directory ma 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 |
Kif tibdel l-NM (Canonical Isem) għal utent fil-Active Directory ma PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
Kif tikseb l-unità organizzattiva (OU) ġenitur ta ‘utent fil-Active Directory ma PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
Kif tikseb l-proprjetarju ta ‘utent (li ħoloq il-kont) fil-Active Directory ma PowerShell?
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
Kif jistgħu jikkonvertu l-attribut PwdLastSet għal utent fil-Active Directory ma PowerShell?
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
Kif biex jittestjaw il-kanal sigur bejn il-kompjuter lokali u l-dominju ma PowerShell?
Test-ComputerSecureChannel
Kif it-tiswija l-kanal sigur bejn il-kompjuter lokali u l-dominju ma PowerShell?
Test-ComputerSecureChannel -Repair
Kif li jiskonnettja kont kompjuter fl-Active Directory ma PowerShell?
Disable-ADAccount $computer
Kif issib kompjuters Operating Systems speċifiċi fil-Active Directory ma 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)
Kif jista ‘jinħoloq unità organizzattiva (OU) fil-Active Directory ma PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
Kif tikseb unità organizzattiva (OU) dettalji fil Active Directory ma PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
Kif tibdel id-deskrizzjoni ta ‘unità organizzattiva (OU) fil-Active Directory ma 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 |
Kif telenka unitajiet organizzattivi vojta (ous) ma 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 } |
Kif tikseb l-manager ta ‘grupp ma PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
Kif estratt ta ‘v4 indirizz IP (80.80.228.8) ma regex ma 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
Kif estratt l-indirizz MAC (C0-D9-62-39-61-2D) ma separatur “-” ma regex ma 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
Kif estratt l-indirizz MAC (C0: D9: 62: 39: 61: 2D) ma separatur “:” bl regex ma 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
Kif estratt data (2015/10/02) ma regex ma PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
Kif estratt URL (www.powershell-guru.com) ma regex ma PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
Kif estratt email (user@domain.com) ma regex ma 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
Kif estratt “guru” mill-eżempju string ma regex ma PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
Kif estratt “guru.com” mill-eżempju string ma regex ma PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
Kif estratt “powershell-guru.com” mill-eżempju string ma regex ma PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
Kif estratt “123” mill-eżempju string ma regex ma PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
Kif estratt “$” (sinjal dollaru) mill-eżempju string ma regex ma PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
Kif biex jissostitwixxu karattru (* Com) ma ‘ieħor (* .fr) fi string ma regex ma PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
Kif jaħarbu string ma regex ma PowerShell?
[regex]::Escape('\\server\share')
Memory
Kif seħħ ġabra ta ‘memorja mill-kollettur żibel mal PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Kif tikseb l-daqs RAM ta ‘kompjuter ma 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
Kif tikseb id-data attwali PowerShell?
Get-Date
[Datetime]::Now
Kif juru d-data fil-formati differenti ma PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
### DATE ### Get-Date -Format d : 15/04/2015 Get-Date -Format D : 15 April 2015 Get-Date -Format f : 15 April 2015 14:57 Get-Date -Format F : 15 April 2015 14:57:34 Get-Date -Format g : 15/04/2015 14:57 Get-Date -Format G : 15/04/2015 14:57:34 Get-Date -Format yyyyMMdd : 20150415 Get-Date -UFormat '%d%m%Y' : 15042015 Get-Date -UFormat '%m%d%Y' : 04152015 Get-Date -UFormat '%Y%m%d' : 20150415 Get-Date -UFormat '%d%m%Y' : 15-04-2015 Get-Date -UFormat '%m%d%Y' : 04-15-2015 Get-Date -UFormat '%Y%m%d' : 2015-04-15 ### HOUR ### Get-Date -Format t : 15:31 Get-Date -Format T : 15:31:44 Get-Date -Format HH : 15 (Hour) Get-Date -Format mm : 57 (Minute) Get-Date -Format ss : 34 (Seconds) Get-Date -DisplayHint Time : 15:31:44 ### DAY ### Get-Date -Format dddd : Wednesday Get-Date -Format ddd : Wed Get-Date -Format dd : 15 ### MONTH ### Get-Date -Format MMMM : April Get-Date -Format MMM : Apr Get-Date -Format MM : 04 ### YEAR ### Get-Date -Format yyyy : 2015 |
Kif jistgħu jikkonvertu data (DateTime) sa data (String) ma PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
Kif jistgħu jikkonvertu data (String) sa data (DateTime) ma PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
Kif tikkalkula d-differenza (numru ta ‘jiem, sigħat, minuti, jew Seconds) bejn żewġ dati ma 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
Kif tqabbel żewġ dati ma 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
Kif biex issolvi firxa ta ‘dati bħal “dateTime” ma PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
Kif tibda u tieqaf stopwatch ma PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
Kif tikseb l-jum kurrenti tal-ġimgħa ma ‘PowerShell?
(Get-Date).DayOfWeek #Sunday
Kif tikseb data bieraħ ma PowerShell?
(Get-Date).AddDays(-1)
Kif tikseb l-għadd ta ‘ġranet fix-xahar (fi Frar 2015) ma PowerShell?
[DateTime]::DaysInMonth(2015, 2)
Kif wieħed ikun jaf sena biżestili ma PowerShell?
[DateTime]::IsLeapYear(2015)
Kif telenka żoni tal-ħin ma PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
Kif jikkodifikaw (sa format ASCII) u jiddekowdja URL mal 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 |
Liema huma l-ekwivalenti ta ‘kmandi tan-netwerk nattivi mal 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 |
Kif tikseb indirizzi IP mal PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
Kif jiskonnettja indirizz IP v6 (IPv6) ma PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
Kif biex jivvalida l-indirizz IP v4 (IPv4) ma PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}
Kif issib l-indirizz IP estern ma 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 } |
Kif issib l-hostname minn indirizz IP ma PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
Kif issib l-indirizz IP minn hostname ma PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
Kif issib l-FQDN minn hostname ma PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
Kif issib l-konfigurazzjoni tan-network (Ip, Subnet, Gateway, u DNS) ma PowerShell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
Kif issib l-indirizz MAC ma PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Kif ping kompjuter bil 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) |
Kif biex jiċċekkjaw jekk il-kompjuter huwa konness mal-internet bil PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
Kif biex iwettqu “whois” lookup għal websajt ma PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
Kif tikseb dettalji ta ‘IP pubbliku (Lokalità ġeografika) ma PowerShell?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
Kif biex jiċċekkjaw jekk port hija miftuħa / magħluqa PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
Kif iwettqu “Tracert” ma PowerShell?
Test-NetConnection www.google.com -TraceRoute
Kif jiffissaw profil konnessjoni tan-netwerk dar mal PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
Kif juru l-konnessjonijiet tal-port TCP ma PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
Kif biex jitqassar URL twil fi URL ċkejkna ma PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
Kif tikseb settings prokura mal PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
Kif biex jiċċekkja l-cache DNS fuq kompjuter lokali ma PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
Kif ċar cache DNS fuq kompjuter lokali ma PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
Kif ċar cache DNS fuq il-kompjuters remoti bl PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
Kif taqra l-Hosts fajl ma PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
Kif biex jiġġeneraw password każwali mal PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
Kif tibdel l-password lokali għal amministratur fuq server remot bl PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
Kif issib l-data ta ‘skadenza password ta’ kont fil-Active Directory ma 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
Kif telenka l-printers għal server speċifiku ma PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
Kif jiġu elenkati l-portijiet kollha għal server speċifiku ma PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
Kif tibdel l-kumment / post ta ‘printer ma 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() |
Kif li jnaddaf (tikkanċella impjiegi kollha) għal printer ma PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
Kif jistampaw paġna tat-test għal printer ma PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
Kif tikseb kjuwijiet print għall-printers bil 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
Kif telenka ġarer reġistru ma PowerShell?
Get-ChildItem -Path Registry::
Kif tikseb valuri tar-reġistru u tipi valur ma 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) } } } |
Kif telenka subkeys ewlenin tar-reġistru ma 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:\' |
Kif telenka subkeys reġistru ewlenin b’mod rikursivi ma PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
Kif issib subkeys ma ‘isem speċifiku PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
Kif jirritornaw biss l-isem ta ‘l-subkeys reġistru ma PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
Kif lista reġistru valuri ma PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
Kif taqra valur reġistru speċifiku ma PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
Kif taqra valur reġistru speċifiku fuq kompjuter remot bl 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
Kif tinħoloq reġistru ewlieni ġdid ma PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'
Kif tinħoloq valur reġistru ma PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
Kif timmodifika valur tar-reġistru eżistenti ma PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
Kif ħassar valur reġistru ma PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
Kif ħassar ewlenin reġistru ma PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
Kif test jekk teżisti reġistru ċentrali ma PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'
Kif test jekk jeżisti valur reġistru ma PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
Kif tneħħi karattri abjad fl-ispazju mill-bidu ta ‘string mal PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
Kif tneħħi karattri abjad fl-ispazju mill-aħħar ta ‘string mal PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
Kif tneħħi karattri abjad-ispazju (li jibda u jispiċċa) ta ‘string mal PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()
Kif jistgħu jikkonvertu string għall-każ ta ‘fuq ma PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()
Kif jistgħu jikkonvertu string biex ibaxxu każ ma PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
Kif tagħżel l-substring “PowerShell” tas-sekwenza “PowerShellGuru” ma PowerShell?
$string.Substring(0,10)
Kif tagħżel l-substring “Guru” tas-sekwenza “PowerShellGuru” ma PowerShell?
$string.Substring(10)
Kif tagħżel in-numru “123” ta ‘”PowerShell123Guru” ma PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
Kif tikseb l-indiċi b’bażi żero ta ‘”Guru” tas-sekwenza “PowerShellGuru” ma PowerShell?
$string.IndexOf('Guru') # 10
Kif biex jiċċekkjaw jekk string huwa null jew vojta ma PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
Kif biex jiċċekkjaw jekk string huwa null, vojta, jew tikkonsisti biss ta ‘karattri abjad ispazju ma’ PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
Kif biex jiċċekkjaw jekk string fiha ittra speċifiku ma PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
Kif jirritornaw it-tul ta ‘string mal PowerShell?
$string.Length
Kif concatenate żewġ kordi mal PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
Kif biex jaqblu għal diversi parentesi waħda jew “[]” fi string mal PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
Kif biex jaqblu għal diversi parentesi waħda jew “()” fi string mal PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
Kif biex jaqblu għal diversi parentesi kaboċċi waħda jew “{}” fi string mal PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
Kif biex jaqblu għal diversi parentesi angolu wieħed jew “<>” fi string mal PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
Kif biex jaqblu xi ittri lowercase (ABC) fi string ma PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
Kif biex jaqblu xi upperletters (ABC) fi string ma PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
Kif jaqblu “[p” (p żgħira) fi string mal PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
Kif jaqblu “[P” (b’ittri kbar P) fi string mal PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
Kif biex jissostitwixxu linja mal-linja ieħor ma PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
Kif jistgħu jikkonvertu operazzjoni diviżjoni għal string (persentaġġ) ma PowerShell?
(1/2).ToString('P')
Kif biex issolvi kordi li jkun fihom numri ma PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
Kif tagħżel l-aħħar kelma ta ‘sentenza ma PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
Kif tikseb l-akbar kelma ta ‘sentenza ma PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
Kif jgħodd in-numru ta ‘drabi string ikun preżenti fiż sentenza ta ma PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
Kif kopja kull karattru string għal firxa karattru ma PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
Kif jistgħu jikkonvertu l-ewwel ittra lill uppercase ta ‘string mal PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
Kif pad (lemin jew xellug) string ma 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 |
Kif jikkodifikaw u jiddekowdja string li Base64 ma 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 |
Kif jistgħu jikkonvertu numru (sa u minn) binarja ma ‘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) |
Kif jirritornaw biss l-aħħar folder parent fi triq ma PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
Kif jirritornaw biss l-aħħar oġġett triq ma PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
Kif jiġu elenkati l-metodi tal-klassi System.Math ma PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
Kif biex jirritorna l-valur assolut bil PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
Kif jirritornaw l-angolu li sine huwa n-numru speċifikat ma PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
Kif jirritornaw il-valur limitu ma PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
Kif jirritornaw il-valur art ma PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
Kif jirritornaw il-naturali (bażi e) logaritmu ta ‘numru speċifikat ma PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
Kif jirritornaw il-bażi ta ’10 logaritmu ta’ numru speċifiku ma PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
Kif biex jirritorna l-massimu ta ‘żewġ valuri ma PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
Kif biex jirritorna l-minimu ta ‘żewġ valuri ma PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
Kif jirritornaw numru jiżdied għal setgħa speċifikata bi PowerShell?
[Math]::Pow(2,4) #Returns 16
Kif jirritornaw valur deċimali sa l-eqreb valur integrali mal PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
Kif biex jirritorna l-parti integrali ta ‘numru deċimali speċifikat ma PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
Kif biex jirritorna l-għerq kwadrat ta ‘numru speċifiku ma PowerShell?
[Math]::Sqrt(16) #Returns 4
Kif jirritornaw il-kostanti PI ma PowerShell?
[Math]::Pi #Returns 3,14159265358979
Kif jirritornaw il-bażi logaritmika naturali (kostanti e) ma PowerShell?
[Math]::E #Returns 2,71828182845905
Kif biex jiċċekkjaw jekk numru huwa saħansitra jew fard ma PowerShell?
[bool]($number%2)
Hashtables
Kif jista ‘jinħoloq hashtable vojta ma PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
Kif tinħoloq hashtable ma ‘oġġetti bil PowerShell?
1 2 3 4 5 |
$hashtable = @{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } |
Kif tinħoloq hashtable magħżula mill ċavetta / isem (dizzjunarju ordnati) ma ‘oġġetti bi PowerShell?
1 2 3 4 5 6 7 |
$hashtable = [ordered]@{ 'Key1' = 'Value1' 'Key2' = 'Value2' 'Key3' = 'Value3' } $hashtable | Get-Member # System.Collections.Specialized.OrderedDictionary |
Kif li jżidu punti (par valur ċavetta) għal hashtable ma PowerShell?
$hashtable.Add('Key3', 'Value3')
Kif tikseb valur speċifiku ta ‘hashtable ma PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
Kif tikseb il-valur minimu ta ‘hashtable ma 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 |
Kif tikseb l-valur massimu ta ‘hashtable ma 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 |
Kif timmodifika oġġetti fi hashtable ma PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
Kif tneħħi oġġetti fil-hashtable ma PowerShell?
$hashtable.Remove('Key1')
Kif ċar ta ‘hashtable ma PowerShell?
$hashtable.Clear()
Kif biex jiċċekkja l-preżenza ta ‘ċavetta / valur speċifiku fil-hashtable ma PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
Kif biex issolvi permezz ewlieni / valur fi hashtable ma PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
Kif toħloq firxa vojta ma PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()
Kif jista ‘jinħoloq firxa ma’ oġġetti bil PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
Kif li jżidu punti ma ‘firxa mal PowerShell?
$array += 'D'
[void]$array.Add('D')
Kif timmodifika oġġett fil-firxa ma PowerShell?
$array[0] = 'Z' # 1st item[0]
Kif biex jiċċekkja l-daqs ta ‘firxa mal PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
Kif sabiex tkun irkuprata oġġett wieħed / ħafna punti kollha / fil-firxa ma PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
Kif tneħħi oġġetti vojta fil-firxa ma PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
Kif biex jiċċekkjaw jekk jeżisti oġġett fil-firxa ma PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
Kif issib in-numru indiċi ta ‘oġġett fil-firxa ma PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
Kif jinqaleb l-ordni ta ‘oġġetti fil-firxa ma PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
Kif tiġġenera oġġett każwali minn firxa ma PowerShell?
$array | Get-Random
Kif biex issolvi firxa fi axxendenti / dixxendenti mod ma PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
Kif jgħodd in-numru ta ‘oġġetti fil-firxa ma PowerShell?
$array.Count
Kif żid firxa għall-ieħor ma PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
Kif issib duplikati minn firxa ma PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
Kif tneħħi duplikati minn firxa ma PowerShell?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
Kif jista ‘jinħoloq firxa ma’ oġġetti li tibda bi prefiss (“user01”, “user02”, … “user10”) ma ‘PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
Kif lista ACL ta ‘utent AD ma PowerShell?
(Get-Acl -Path "AD:\$dn").Access
Kif li lista ACL ta folder mal PowerShell?
(Get-Acl -Path C:\scripts).Access
Kif telenka iskrizzjonijiet speċifiċi permess ACL (utenti jew gruppi) ta ‘utent AD ma 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
Liema huma l-aktar tipi komuni ta ‘dejta ma’ 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 |
Kif issib l-valuri minimi u massimi għal xi varjabbli tip ma 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 |
Kif biex jittestjaw il-datatype ma PowerShell?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
Kif tinħoloq Hawnhekk-String varjabbli ma 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} "@ |
Kif tinħoloq varjabbli ma PowerShell?
$powershellGuru = 'Hello'
Kif tinħoloq varjabbli kostanti mal PowerShell?
Set-Variable -Name powershellGuru -Value 2015 -Option Constant
Kif tinħoloq varjabbli globali ma PowerShell?
$Global:powershellGuru = 'Hello'
Kif jaqraw varjabbli ma PowerShell?
$powershellGuru = 'Hello' # Create
$powershellGuru # Read
Get-Variable -Name powershellGuru -ValueOnly # Read