Concept: The questions wey people dey ask pass about Powershell.
You fit use this list for different ways:
- To copy/paste commands into a script
- To see quickly the syntax for one ogbonge command
- To range yake improve your technical knowledge
- To range take know new commands
- To prepare one job interview
Updated |
2015/28/06
|
Writer | powershell-guru.com |
Source | pidgin-english.powershell-guru.com |
Categories |
75
|
Questions |
610
|
System
How I go fit sabi my own ogbonge version of PowerShell?
1 2 3 4 5 6 7 8 9 |
# via Powershell $PSVersionTable.PSVersion.Major # via Registry (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine').PowerShellVersion # Versions 1 and 2 (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine').PowerShellVersion # Versions 3 and 4 # via Remote Invoke-Command -ComputerName $computer -ScriptBlock { $PSVersionTable.PSVersion.Major } |
How person go take run PowerShell for another version wey don tay?
powershell.exe -Version 2.0
How to take get small sekele PowerShell version (3.0 and the one wey dey higher) for script with PowerShell?
#Requires -Version 3.0
How to take get chance run things for a script with PowerShell?
1 2 3 4 5 |
# Solution 1 #Requires -RunAsAdministrator # Solution 2 [bool]((whoami.exe /all) -match 'S-1-16-12288') |
How to confirm levels for script with PowerShell?
help -Name .\Get-ExchangeEnvironmentReport.ps1 -Full
How to get informate for the person wey still dey use PowerShell?
[Security.Principal.WindowsIdentity]::GetCurrent()
How person go fit create, edit, and reload profile with 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 |
How person go take press pause of 5 seconds/minutes inside a script with PowerShell?
Start-Sleep -Seconds 5
Start-Sleep -Seconds 300 # 5 minutes
How to person go get the last boot time with PowerShell?
(Get-CimInstance -ClassName win32_operatingsystem).LastBootUpTime
How person go fit get the type accelerators with 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 |
How to take arrange the startup programs with PowerShell?
1 |
Get-WmiObject -Class Win32_StartupCommand | Sort-Object -Property Caption | Format-Table -Property Caption, Command, User -AutoSize |
How to commot one kind application with PowerShell?
1 2 |
$application = Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name LIKE 'HP Recovery Manager'" $application.Uninstall() |
How person go take screenphoto of the whole desktop or of window wey dey on with PowerShell?
Take-ScreenShot -Screen -File 'C:\scripts\screenshot.png' -Imagetype JPEG
Repository : Take-ScreenShot
How person go fit to take count message for MSMQ queues with PowerShell?
1 |
Get-WmiObject -Class Win32_PerfRawData_MSMQ_MSMQQueue -ComputerName $computer | Format-Table -Property Name, MessagesInQueue -AutoSize |
How person go take to set execution matter with 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 |
How to take make cut corner with 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() |
How to take hold or commot one program for taskbar with 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') |
How take open a Windows Explorer with PowerShell?
[Diagnostics.Process]::Start('explorer.exe')
Invoke-Item -Path C:\Windows\explorer.exe
How to take arrange device drivers with PowerShell?
Get-WmiObject -Class Win32_PnPSignedDriver
Get-WindowsDriver -Online -All
driverquery.exe
How to take make GUID with 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') |
How to fit locate the place of temporary directory for the person wey still be user with PowerShell?
[System.IO.Path]::GetTempPath()
How to fit join one path and one child path into one single path with PowerShell?
Join-Path -Path C:\ -ChildPath \windows
How to take arrange all cmdlets “Get-*” with PowerShell?
Get-Command -Verb Get
How to take arrange ogbonge system folders with PowerShell?
1 |
[System.Enum]::GetNames([System.Environment+SpecialFolder]) | ForEach-Object -Process { $_ + " [System.Environment]::GetFolderPath($_)" } |
How to take carry-up ISO/VHD files with PowerShell?
Mount-DiskImage 'D:\ISO\file.iso' # ISO
Mount-DiskImage 'D:\VHD\file.vhd' # VHD
How to fit check .NET Framework versions wey dem put with 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 |
How to fit check wether the .NET Framework version 4.5 dey with PowerShell?
(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -EA 0).Version -like '4.5*'
How to take start and stop program wey dey (to create a record of the Windows PowerShell session) with PowerShell?
Start-Transcript -Path 'C:\scripts\transcript.txt
Stop-Transcript
How to take change the directory wey dey now to one koko location with PowerShell?
Set-Location -Path 'C:\scripts'
How to take commot the screen with PowerShell?
Clear-Host
cls # Alias
How to take change resolution of the thing wey dey show with PowerShell?
Set-DisplayResolution -Width 1280 -Height 1024 -Force # Windows 2012
How to take arrange the “full screen” window with PowerShell?
mode.com 300
How to take get the size (how e wide and how e tall) of one picture with 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 } |
How person go fit get the Windows product key with 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
How person go fit get the current “% Processor Time” (wey be average) in the last 5 seconds (10 times) with PowerShell?
(Get-Counter '\Processor(_total)\% Processor Time' -SampleInterval 5 -MaxSamples 10).CounterSamples.CookedValue
Assemblies
How person go fit put load for assemblies with 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') |
How to take check current .NET load wey dey assemblies with 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*' } |
How person go take find GAC (Global Assembly Cache) path with PowerShell?
1 |
(New-Object -TypeName Regex -ArgumentList '(?<=file:///)(.*)(?=\/GAC)', 'IgnoreCase').Match(([PSObject].Assembly.Evidence | Where-Object -FilterScript { $_.Value -ne $null }).Value).Value -replace '/', '\' |
Clipboard
How to take dubb results to the clipboard with PowerShell?
1 |
Get-Process | clip.exe |
How person go take get the thing wey dey for the clipboard with PowerShell?
Add-Type -AssemblyName PresentationCore
[Windows.Clipboard]::GetText()
Hotfixes
How to take get put hotfixes with PowerShell?
Get-HotFix -ComputerName $computer
How to take arrange put the hotfixes before/after one koko date with 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
How to take look wether dem put hotfix with PowerShell?
Get-HotFix -Id KB2965142
How to take arrange put hotfixes inside one remote computer with PowerShell?
Get-HotFix -ComputerName $computer
Pagefile
How to take get Pagefile informate with PowerShell?
Get-WmiObject -Class Win32_PageFileusage | Select-Object -Property Name, CurrentUsage, AllocatedBaseSize, PeakUsage, InstallDate
How to take get the recommended size (MB) for the Pagefile with PowerShell?
[Math]::Truncate(((Get-WmiObject -Class Win32_ComputerSystem).TotalPhysicalMemory) / 1MB) * 1.5
How to arrange one Pagefile (4096 MB) on the (D:) drive with PowerShell?
1 2 3 4 5 |
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{ Name = 'D:\pagefile.sys' InitialSize = 4096 MaximumSize = 4096 } |
How to commot one Pagefile wey dey on (C:) drive with 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
How to look for the pieces of one drive with PowerShell?
1 |
$drive = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter = 'c:'" $defragReport = $drive.DefragAnalysis() $defragReport.DefragAnalysis |
How to look inside the disk space of drives with 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
How to take open one file with PowerShell?
Invoke-Item -Path 'C:\scripts\file.txt'
.'C:\scripts\file.txt'
How person go fit read one file with PowerShell?
Get-Content -Path 'C:\scripts\file.txt'
gc "C:\scripts\file.txt" # Alias
How to take write something out to one file with PowerShell?
'Line1', 'Line2', 'Line3' | Out-File -FilePath 'C:\scripts\file.txt'
'Line1', 'Line2', 'Line3' | Add-Content -Path file.txt
How to get the ogbongename for the script wey still dey file with PowerShell?
$MyInvocation.MyCommand.Path
How to pressdown /zip files with PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder,$fileZIP)
How to leave/unzip files with PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::ExtractToDirectory($fileZIP, $folder)
How to take see the files wey dey inside ZIP store with PowerShell?
Add-Type -AssemblyName 'System.IO.Compression.Filesystem'
[System.IO.Compression.ZipFile]::OpenRead($fileZIP)
How to show the size of one file in KB with PowerShell?
(Get-ChildItem -Path .\winsrv.dll).Length /1KB
(Get-ChildItem -Path .\winsrv.dll).Length /1MB
(Get-ChildItem -Path .\winsrv.dll).Length /1GB
How to take find the files wey big well-well or wey dey smaller than 1 GB with 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} |
How to take show the name of one file and make e no extend with PowerShell?
[System.IO.Path]::GetFileNameWithoutExtension('C:\Windows\system32\calc.exe') # Return calc
How to take show the extension of one file with PowerShell?
[System.IO.Path]::GetExtension('C:\scripts\file.txt') # Return .txt
How person go fit get the version of one file with PowerShell?
1 2 |
(Get-Item -Path C:\Windows\System32\calc.exe).VersionInfo.FileVersion [System.Diagnostics.FileVersionInfo]::GetVersionInfo('C:\Windows\system32\calc.exe').FileVersion |
How to take get the hash for one file with PowerShell?
(Get-FileHash $file).Hash
How to take get the MD5/SHA1 checksum for one file with PowerShell?
Get-FileHash $file -Algorithm MD5
Get-FileHash $file -Algorithm SHA1
How to take show files wey dey hide with PowerShell?
1 2 3 4 5 |
# Display only hidden files Get-ChildItem -Hidden -File # Display all files (including hidden files) Get-ChildItem -Force -File |
How to look if one file get him own extension with PowerShell?
1 |
[System.IO.Path]::HasExtension('C:\hiberfil.sys') |
How to arrange one file make e be “Read Only” with PowerShell?
Set-ItemProperty -Path .\file.txt -Name IsReadOnly -Value $true
How to take change the “LastWriteTime” attribute wey be last week own for one file with PowerShell?
Set-ItemProperty -Path .\file.txt -Name LastWriteTime -Value ((Get-Date).AddDays(-7))
If not working, use Nirsoft tool: BulkFileChanger.
How to take arrange one new file with PowerShell?
New-Item -ItemType File -Path 'C:\scripts\file.txt' -Value 'FirstLine'
How to take re-arrangename one file with PowerShell?
Rename-Item -Path 'C:\scripts\file.txt' -NewName 'C:\scripts\powershellguru2.txt'
How person go fit bulk/batch re-arrangename plenty files with PowerShell?
Get-ChildItem -Path C:\scripts\txt | Rename-Item -NewName { $_.Name -replace ' ', '_' }
How to take commot one file with PowerShell?
Remove-Item -Path 'C:\scripts\file.txt'
How to take show the 10 latest lines for one file with PowerShell?
Get-Content -Path 'C:\scripts\log.txt' -Tail 10
How to take remove block from plenty files of one folder with PowerShell?
Get-ChildItem -Path 'C:\scripts\Modules' | Unblock-File
How to take commot line wey dey empty from one file with PowerShell?
(Get-Content -Path file.txt) | Where-Object -FilterScript {$_.Trim() -ne '' } | Set-Content -Path file.txt
How to look wether one file dey exists with PowerShell?
1 |
Test-Path -Path 'C:\Windows\notepad.exe' # Return True |
How person go fit get the newest/oldest file wey dem arrange inside one folder with 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 |
How to take commot another lines from one file with 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 |
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 |
How to take carry commot the value for one variable to one file with PowerShell?
Set-Content -Path file.txt -Value $variable
How to take count the number of files (*.txt) wey dey inside one folder with 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 |
How to look for one string inside plenty files with PowerShell?
Select-String -Path 'C:\*.txt' -Pattern 'Test'
How to take show the first/last line for one file with 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 |
How to take show one ogbonge line number for one file with 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 |
How to take count the number of lines wey dey for one file with PowerShell?
1 2 |
'Line1', 'Line2', 'Line3' | Out-File -FilePath file.txt (Get-Content -Path .\file.txt | Measure-Object -Line).Lines # Returns 3 |
How to take count the number of characters and words wey dey for one file with 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 |
How to take collect one file with PowerShell?
Invoke-WebRequest -Uri 'http://www.nirsoft.net/utils/searchmyfiles.zip' -OutFile 'C:\tools\searchmyfiles.zip'
How to take show full path for one file with PowerShell?
Resolve-Path -Path .\script.ps1 # Return C:\Scripts\script.ps1
Copy
How to take dubb one file to one folder with PowerShell?
Copy-Item -Path 'C:\source\file.txt' -Destination 'C:\destination'
How to take dubb one file to plenty folders with PowerShell?
1 2 |
$destination = 'C:\destination\Folder1', 'C:\destination\Folder2' $destination | Copy-Item -Path 'C:\source\file.txt' -Recurse -Destination {$_} |
How to take dubb plenty files to one folder with PowerShell?
Get-ChildItem -Path 'C:\source' -Filter *.txt | Copy-Item -Destination 'C:\destination'
Active Directory
Domain & Forest
How to take look for Global Catalog servers inside Active Directory with PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs
How to take look for places inside Active Directory with PowerShell?
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
How to take look for the current domain controller with PowerShell?
(Get-ADDomainController).HostName
How to take look for all the domain controllers inside one domain with 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} |
How to take look for the AD replication failures with PowerShell?
Get-ADReplicationFailure dc02.domain.com # Windows 8 and 2012
How to take look for the tombstone lifetime for the forest inside Active Directory with PowerShell?
1 |
(Get-ADObject -Identity "cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi]('LDAP://RootDSE')).configurationNamingContext)" -Properties tombstonelifetime).tombstonelifetime |
How to take get the details for the forest/domain inside Active Directory with PowerShell?
1 2 |
Get-ADDomain domain.com Get-ADForest domain.com |
How to take get the path of the “Objects wey dem Commot” container inside Active Directory with PowerShell?
(Get-ADDomain).DeletedObjectsContainer
How to range take allow the AD Recycle Bin feature inside Active Directory with 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' |
How person go fit put AD Account back from the Recycle Bin inside Active Directory with PowerShell?
Get-ADObject -Filter 'samaccountname -eq "powershellguru"' -IncludeDeletedObjects | Restore-ADObject
How to take look for the FSMO roles with 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 |
How to take connect to one specific domain controller with PowerShell?
Get-ADUser -Identity $user -Server 'serverDC01'
How person go fit get the logon wey still dey server with PowerShell?
1 2 |
($env:LOGONSERVER).Substring(2) ([System.Environment]::GetEnvironmentVariable('logonserver')).Substring(2) |
How to take do “gpupdate” for inside one computer with PowerShell?
Invoke-GPUpdate -Computer $computer -Force -RandomDelayInMinutes 0 # Windows 2012
Groups
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' |
How to take commot one group for inside Active Directory with PowerShell?
Remove-ADGroup -Identity 'PowershellGuru'
How to take put one person wey be user to one group inside Active Directory with PowerShell?
Add-ADGroupMember "Powershell Guru" -Members powershellguru
How to take commot one person wey be user from one group inside Active Directory with PowerShell?
Remove-ADGroupMember 'Powershell Guru' -Members powershellguru
How to take look for empty groups (wey been no get members) inside Active Directory with PowerShell?
Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}
How to take count empty groups (wey been no get members) inside Active Directory with PowerShell?
(Get-ADGroup -Filter * -Properties Members | Where-Object -FilterScript {-not $_.Members}).Count
How to take get the members of one group inside Active Directory with PowerShell?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Solution 1 Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname} # Solution 2 Get-ADGroup 'Powershell Guru' -Properties Members | Select-Object -Property Members -ExpandProperty Members | Sort-Object # Solution 3 function Get-ADGroupMemberFast { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string]$GroupName ) $de = New-Object -TypeName System.DirectoryServices.DirectoryEntry $ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher $ds.SearchRoot = $de $ds.Filter = "(cn=$group)" $null = $ds.PropertiesToLoad.Add('member') $result = $ds.FindOne() if($result) { $account = $result.GetDirectoryEntry() $account.Properties['member'] | ForEach-Object -Process {$_} } } Get-ADGroupMemberFast -GroupName 'Powershell Guru' |
1 2 |
Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.DistinguishedName} Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.SamAccountName} |
1 2 |
(Get-ADGroupMember 'Powershell Guru' | ForEach-Object -Process {$_.Samaccountname}).Count (Get-ADGroupMember 'Powershell Guru' -Recursive | ForEach-Object -Process {$_.Samaccountname}).Count |
Users
1 2 3 4 5 6 7 8 9 |
# Filter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like '*vip*'} -Properties Name).Name # LDAPFilter (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -LDAPFilter '(name=*vip*)' -Properties Name).Name # With a variable $user = '*vip*' (Get-ADUser -SearchBase 'OU=myOU,DC=domain,DC=com' -Filter {name -like $user} -Properties Name).Name |
How to take move one user to inside another OU inside Active Directory with PowerShell?
Move-ADObject -Identity $dn -TargetPath 'OU=myOU,DC=domain,DC=com'
How to take look for all the Members wey dey (Nested) for one user with PowerShell?
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($dn))"
How to take get the Members (short name/scatter) for one user with 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 |
How to change the way wey dem take Describe, Office, and Telephone number for one person wey dey use account inside Active Directory with 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 |
How to take open one person wey dey use account inside Active Directory with PowerShell?
Unlock-ADAccount $samAccountName
1 2 |
Disable-ADAccount $samAccountName Enable-ADAccount $samAccountName |
How to take commot one person wey dey use account inside Active Directory with PowerShell?
Remove-ADUser $samAccountName
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 |
How to take look for the person wey get one file inside Active Directory with 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 |
How to take look for the OU (Organizational Unit) for one person wey dey be user inside Active Directory with PowerShell?
[regex]::match("$((Get-ADUser $user -Properties DistinguishedName).DistinguishedName)",'(?=OU=)(.*\n?)').value
How to look for person wey no dey use accounts again inside Active Directory with PowerShell?
1 2 |
Search-ADAccount -AccountDisabled Get-ADUser -Filter {Enabled -ne $true} |
How to look for person wey him account don expire inside Active Directory with PowerShell?
Search-ADAccount -AccountExpired
How to look for person wey dem don lock him accounts inside Active Directory with PowerShell?
Search-ADAccount -LockedOut
How to look for the SID for one person wey dey use account inside Active Directory with PowerShell?
(Get-ADUser $user -Properties SID).SID.Value
1 2 |
$user = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList ('DOMAIN', 'user') $SID = ($user.Translate([System.Security.Principal.SecurityIdentifier])).Value |
How to change one SID to name of one person wey get account inside Active Directory with PowerShell?
1 2 |
$SID = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList ('SID') $user = ($SID.Translate( [System.Security.Principal.NTAccount])).Value |
1 2 3 |
$dn = 'CN=Powershell Test,OU=TEST,DC=domain,DC=com' $dn.Split(',')[0] # Returns "CN=Powershell Test" $dn.Split(',')[0].Split('=')[1] # Returns "Powershell Test" |
How to take look for the date wey dem create/modification for one person wey dey useraccount inside Active Directory with 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 |
How to take get the LDAP road for one person wey dey use inside Active Directory with 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 |
How to take change the CN (Canonical Name) for one person wey dey use account inside Active Directory with PowerShell?
Rename-ADObject $((Get-ADUser $user -Properties DistinguishedName).DistinguishedName) -NewName 'Test Powershell'
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $parent = $dn.Split(',',2)[1] |
1 2 |
$dn = (Get-ADUser $user -Properties DistinguishedName).DistinguishedName $owner = (Get-Acl -Path "AD:$dn").Owner |
1 2 3 4 5 |
# Solution 1 [DateTime]::FromFileTime((Get-ADUser $user -Properties pwdLastSet).pwdLastSet) # Solution 2 w32tm /ntte 130787549514737594 |
Computers
How to take test the channel wey dey safe between the local computer and the domain with PowerShell?
Test-ComputerSecureChannel
How to take repair the safe channel between the local computer and the domain with PowerShell?
Test-ComputerSecureChannel -Repair
How to take make one account for computer make e no work inside Active Directory with PowerShell?
Disable-ADAccount $computer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Get-ADComputer -Filter 'OperatingSystem -eq "CentOS"' Get-ADComputer -Filter 'OperatingSystem -eq "GNU/Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Linux"' Get-ADComputer -Filter 'OperatingSystem -eq "Mac OS X"' Get-ADComputer -Filter 'OperatingSystem -eq "OnTap"' Get-ADComputer -Filter 'OperatingSystem -eq "Red Hat Enterprise Linux Server"' Get-ADComputer -Filter 'OperatingSystem -eq "redhat-linux-gnu"' Get-ADComputer -Filter 'OperatingSystem -eq "Samba"' Get-ADComputer -Filter 'OperatingSystem -eq "Ubuntu"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows NT"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 2000 Server"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows XP Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2003"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Business"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Vista™ Entreprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Professional"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 7 Ultimate"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2008 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server® 2008 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows 8.1 Enterprise"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 R2 Standard"' Get-ADComputer -Filter 'OperatingSystem -eq "Windows Server 2012 Standard"' |
Organizational Unit (OU)
How to take create one Organizational Unit (OU) inside Active Directory with PowerShell?
New-ADOrganizationalUnit -Name 'TEST' -Path 'DC=domain,DC=com'
How to take get Organizational Unit (OU) tori inside Active Directory with PowerShell?
Get-ADOrganizationalUnit 'OU=TEST,DC=domain,DC=com' -Properties *
How to take change the describe for one Organizational Unit (OU) inside Active Directory with 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 |
How to take remove list for Organizational Units (OUs) with 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 } |
How to take get the manager for one group with PowerShell?
(Get-ADGroup $dn -Properties Managedby).Managedby
Regex (Regular Expression)
How to take gather one IP address v4 (80.80.228.8) with Regex with 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
How to take gather one MAC address (C0-D9-62-39-61-2D) with separator “-” with Regex with 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
How to take gather one MAC address (C0:D9:62:39:61:2D) with separator “:” with Regex with 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
How to take gather one date (10/02/2015) with Regex with PowerShell?
$example = 'The date is 10/02/2015'
$date = [regex]::match($example,'(\d{2}\/\d{2}\/\d{4})').value
How to take gather one URL (www.powershell-guru.com) with Regex with PowerShell?
$example = 'The URL is www.powershell-guru.com'
$url = [regex]::match($example,'[a-z]+[:.].*?(?=\s)').value
How to take gather one email (user@domain.com) with Regex with 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
How to take gather “guru” from the string example with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?=.com)').value
How to take gather “guru.com” from the string example with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=-)(.*\n?)(?<=.)').value
How to take gather “powershell-guru.com” from the string example with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::match($example,'(?<=www.)(.*\n?)').value
How to take gather “123” from the string example with Regex with PowerShell?
$example = 'Powershell123'
[regex]::match($example,'(\d+)').value
How to take gather “$” (dollar sign) from the string example with Regex with PowerShell?
$example = 'Powershell`$123'
[regex]::match($example,'(\$)').value
How to take change one character (*.com) with another (*.fr) inside one string with Regex with PowerShell?
$example = 'www.powershell-guru.com'
[regex]::Replace($example, '.com','.fr')
How to take escape one string with Regex with PowerShell?
[regex]::Escape('\\server\share')
Memory
How to by-force one collection of memory by the garbage collector with PowerShell?
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
How to take get the RAM size of one computer with 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
How to take get the current date with PowerShell?
Get-Date
[Datetime]::Now
How to take show the date inside different formats with 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 |
How to change one date (Datetime) to one date (String) with PowerShell?
$datetimeToString = '{0:dd/MM/yy}' -f (Get-Date 30/01/2015)
$datetimeToString = (Get-Date 31/01/2015).ToShortDateString()
How to change one date (String) to one date (Datetime) with PowerShell?
$stringToDatetime = [Datetime]::ParseExact('30/01/2015', 'dd/MM/yyyy', $null)
How to take arrange calculate the difference (number of Days, Hours, Minutes, or Seconds) between two dates with 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
How to take relate two dates with 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
How to take arrange one array of dates as “Datetime” with PowerShell?
$arrayDate | Sort-Object -Property {$_ -as [Datetime]}
How to take start and stop one stopwatch with PowerShell?
$chrono = [Diagnostics.Stopwatch]::StartNew()
$chrono.Stop()
$chrono
How to take get the current day of the week with PowerShell?
(Get-Date).DayOfWeek #Sunday
How to take get yesterday’s date with PowerShell?
(Get-Date).AddDays(-1)
How to take get the number of days inside one month (for February 2015) with PowerShell?
[DateTime]::DaysInMonth(2015, 2)
How to take know one leap year with PowerShell?
[DateTime]::IsLeapYear(2015)
How to take arrange time zones with PowerShell?
[System.TimeZoneInfo]::GetSystemTimeZones()
Networking
How to take put code (to ASCII format) and commot code from URL with 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 |
Wetin be the equivalents for native network commands with 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 |
How to take get IP addresses with PowerShell?
Get-NetIPAddress # Windows 8.1 & Windows 2012
Get-NetIPConfiguration # Windows 8.1 & Windows 2012
How to take make IP address v6 make e no work (IPv6) with PowerShell?
1 |
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters' -Name 'DisabledComponents' -Value '0xFFFFFFFF' -PropertyType"DWORD" # Reboot required |
How to take make sure an IP address v4 (IPv4) with PowerShell?
if([ipaddress]'10.0.0.1'){'validated'}
How to take look for the external IP address with 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 } |
How to take look for the Hostname from one IP address with PowerShell?
([System.Net.Dns]::GetHostEntry($IP)).Hostname
How to look for the IP address from one Hostname with PowerShell?
([System.Net.Dns]::GetHostAddresses($computer)).IPAddressToString
How to take look for the FQDN from one Hostname with PowerShell?
[System.Net.Dns]::GetHostByName($computer).HostName
How to take look for the network configuration (Ip, Subnet, Gateway, and DNS) with PowerShell?
1 |
Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Format-Table -Property Description, IpAddress, IPSubnet, DefaultIPGateway, DNSServerSearchOrder |
How to take look for the MAC address with PowerShell?
Get-CimInstance win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
Get-WmiObject -Class win32_networkadapterconfiguration | Select-Object -Property Description, Macaddress
How to take ping one computer with 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) |
How to take check if one computer dey connected to the internet with PowerShell?
1 |
[Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]'{DCB00C01-570F-4A9B-8D69-199FDBA5723B}')).IsConnectedToInternet |
How to take perform one “whois” lookup for one website with PowerShell?
$whois = New-WebServiceProxy 'http://www.webservicex.net/whois.asmx?WSDL'
$whois.GetWhoIs('powershell-guru.com')
How to take get full tori for one public IP (Geolocation) with PowerShell?
1 2 |
$externalIP = (Invoke-WebRequest -Uri 'myexternalip.com/raw').Content $detailsIP = ([xml](Invoke-WebRequest -Uri "http://freegeoip.net/xml/$externalIP" -UseBasicParsing).Content).Response |
How to take check if one port dey open/closed with PowerShell?
New-Object -TypeName Net.Sockets.TcpClient -ArgumentList $computer, 135
How to take perform “tracert” with PowerShell?
Test-NetConnection www.google.com -TraceRoute
How to take connect one home network connection profile with PowerShell?
Get-NetAdapter | Format-Table -Property Name, InterfaceDescription, ifIndex -AutoSize # Windows 8.1
Set-NetConnectionProfile -InterfaceIndex 6 -NetworkCategory Private
How to take show the TCP port connections with PowerShell?
netstat.exe -ano
Get-NetTCPConnection #Windows 8 and 2012
How to take make long URL to become short into one tiny URL with PowerShell?
$url = 'www.powershell-guru.com'
$tiny = Invoke-RestMethod -Uri "http://tinyurl.com/api-create.php?url=$url"
How to take get proxy settings with PowerShell?
Get-ItemProperty -Path HKCU:"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
DNS
How to take check the DNS cache on one local computer with PowerShell?
ipconfig.exe /displaydns
Get-DnsClientCache #Windows 8 and 2012
How to take clear one DNS cache on one local computer with PowerShell?
ipconfig.exe /flushdns
Start-Process -FilePath ipconfig -ArgumentList /flushdns -WindowStyle Hidden
Clear-DnsClientCache #Windows 8 and 2012
How to take clear one DNS cache on remote computers with PowerShell?
Invoke-Command -ScriptBlock {Clear-DnsClientCache} -ComputerName computer01, computer02
How to take read the Hosts file with PowerShell?
Get-Content -Path 'C:\Windows\system32\drivers\etc\hosts'
Password
How to take gather one random password with PowerShell?
[Reflection.Assembly]::LoadWithPartialName('System.Web')
[System.Web.Security.Membership]::GeneratePassword(30,2)
How to take change the local password for one administrator on one remote server with PowerShell?
$admin = [ADSI]('WinNT://server01/administrator,user')
$admin.SetPassword($password)
$admin.SetInfo()
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
How to take arrange list for all the printers for one ogbonge server with PowerShell?
Get-WmiObject -Query 'Select * From Win32_Printer' -ComputerName $computer
How to take arrange list for all the ports for one specific server with PowerShell?
Get-WmiObject -Class Win32_TCPIPPrinterPort -Namespace 'root\CIMV2' -ComputerName $computer
How to take change the comment/location for one printer with 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() |
How to take commot (cancel all the works) wey waka enter one printer with PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.CancelAllJobs()
How to take test one page for printer with PowerShell?
$printer = Get-WmiObject -Class win32_printer -Filter "Name='HP Deskjet 2540 series'"
$printer.PrintTestPage()
How to take get print wey don arrange for printers with 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
How to take arrange list registry hives with PowerShell?
Get-ChildItem -Path Registry::
How to take get ogbonge value for registry and the kind of value with 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) } } } |
How to take waka arrange list registry key subkeys with 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:\' |
How to take waka arrange list registry key subkeys in a recursive way with PowerShell?
Get-ChildItem -Path 'HKLM:\SYSTEM' -Recurse -ErrorAction SilentlyContinue
How to range take look for subkeys with one ogbonge name with PowerShell?
Get-ChildItem -Path 'HKLM:\SOFTWARE' -Include *Plugin* -Recurse -ErrorAction SilentlyContinue
How to take return only the name of the registry wey dey subkeys with PowerShell?
(Get-ChildItem -Path 'HKLM:\SYSTEM').Name # Return HKEY_LOCAL_MACHINE\SYSTEM\ControlSet
Get-ChildItem -Path 'HKLM:\SYSTEM' -Name # Return ControlSet
How to take waka arrange list for registry values with PowerShell?
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion'
How to read one ogbonge registry wey get value with PowerShell?
(Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').ProductName
How to take read one ogbonge registry wey get value on top one local computer with 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
How to take create one new registry key with PowerShell?
New-Item -Path 'HKCU:\Software\MyApplication'
How to take create one registry wey get value with PowerShell?
New-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '1.0'
How to take modify one registry value wey don dey before with PowerShell?
Set-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version' -Value '2.0'
Delete
How to take commot one registry wey get value with PowerShell?
Remove-ItemProperty -Path 'HKCU:\Software\MyApplication' -Name 'Version'
How to take commot one registry key with PowerShell?
Remove-Item -Path 'HKCU:\Software\MyApplication' -Force
Test
How to take arrange test wether one registry key dey exist with PowerShell?
Test-Path -Path 'HKCU:\Software\MyApplication'
How to take arrange test wether one registry value dey exist with PowerShell?
(Get-Item -Path 'HKCU:\Software\MyApplication').GetValueNames() -contains 'Version'
Strings
How to take commot white-space characters from the beginning of one string with PowerShell?
$string = ' PowershellGuru'
$string = $string.TrimStart()
How to take commot white-space characters from the end of one string with PowerShell?
$string = 'PowershellGuru '
$string = $string.TrimEnd()
How to take commot white-space characters (from the start and to the end) of one string with PowerShell?
$string = ' PowershellGuru '
$string = $string.Trim()
How to take convert one string to upper case with PowerShell?
$string = 'powershellguru'
$string = $string.ToUpper()
How to take convert one string to lower case with PowerShell?
$string = 'POWERSHELLGURU'
$string = $string.ToLower()
How to take arrange select the substring “PowerShell” of the string “PowerShellGuru” with PowerShell?
$string.Substring(0,10)
How to take arrange select the substring “Guru” of the string “PowerShellGuru” with PowerShell?
$string.Substring(10)
How to take arrange select the number “123” of “PowerShell123Guru” with PowerShell?
$string = 'Powershell123Guru'
[regex]::match($string,'(\d+)').value
How to take arrange get the zero-based index of “Guru” of the string “PowerShellGuru” with PowerShell?
$string.IndexOf('Guru') # 10
How to take check wether one string no dey or dey empty with PowerShell?
$string = $null
$string = ''
[string]::IsNullOrEmpty($string)
How to take check wether one string no dey, empty, or been get only white-space characters with PowerShell?
$string = $null
$string = ''
$string = ' '
[string]::IsNullOrWhiteSpace($string)
How to take check wether one string been get one ogbonge letter with PowerShell?
$string = 'PowershellGuru'
$string.Contains('s')
[regex]::match($string,'s').Success
How to take return the length of one string with PowerShell?
$string.Length
How to take concatenate two strings with PowerShell?
1 2 3 4 5 6 7 |
# Solution 1 $string1 + $string2 # Solution 2 $string1 = 'Powershell' $string2 = 'Guru' [string]::Concat($string1,$string2) |
How to take arrange together for one or plenty brackets “[ ]” inside one string with PowerShell?
$string = '[PowershellGuru]'
$string -match '\[' # Only 1
$string -match '\[(.*)\]' # Several
How to take arrange together for one or plenty parentheses “( )” inside one string with PowerShell?
$string = '(PowershellGuru)'
$string -match '\(' # Only 1
$string -match '\((.*)\)' # Several
How to take arrange match for one or plenty curly brackets “{ }” inside one string with PowerShell?
$string = '{PowershellGuru}'
$string -match '\{' # Only 1
$string -match '\{(.*)\}' # Several
How to take arrange match for one orplenty angle brackets “< >” inside one string with PowerShell?
$string = ''
$string -match '\<' # Only 1
$string -match "\<(.*)\>" # Several
How to take arrange match any lowercase letters (abc) inside one string with PowerShell?
$string = 'POWERSHELLGURU'
$string -cmatch "^[a-z]*$" #False
How to take arrange match any upperletters (ABC) inside one string with PowerShell?
$string = 'powershellguru'
$string -cmatch "^[A-Z]*$" #False
How to take arrange match “[p” (p lower case) inside one string with PowerShell?
$string = '[powershellGuru]'
$string -cmatch '\[[a-z]\w+' #True
How to take arrange match “[P” (P upper case) inside one string with PowerShell?
$string = '[PowershellGuru]'
$string -cmatch '\[[A-Z]\w+' #True
How to take put another line with another line with PowerShell?
$a = 'Line A'
$b = 'Line B'
$a = $a -replace $a, $b
How to take turn one division operation to one string (percentage) with PowerShell?
(1/2).ToString('P')
How to take arrange separate strings containing numbers with PowerShell?
1 |
'string-10', 'string-2', 'string-23', 'string-30' | Sort-Object -Property {$_ -replace '[\d]'}, {$_ -replace '[a-zA-Z\p{P}]'-as [int]} |
How to arrange choose the last word of one sentence with PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ')[-1] # Returns Powershell
How to take get the largest word of one sentence with PowerShell?
$sentence = 'My name is Test Powershell'
$sentence.Split(' ') | Sort-Object -Property Length | Select-Object -Last 1 # Returns Powershell
How to take range count the number of times wey one string dey present inside one sentence with PowerShell?
$sentence = 'test test test Powershell'
[regex]::Matches($sentence, 'test').Count # Returns 3
How to take copy one by one character inside one string to one character array with PowerShell?
1 2 3 4 5 6 7 |
$name = 'test' $name.ToCharArray() s t e v e |
How to take turn the first letter to uppercase of one string with PowerShell?
1 2 |
$name = 'test' $name.Substring(0,1).ToUpper() + $name.Substring(1) |
How to take pad (left or right) one string with 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 |
How to take put code and remove code from string to Base64 with 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 |
How to take turn one number (to and from) binary with 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) |
How to take return only the last parent folder inside one path with PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path (Split-Path -Path $path -Parent) -Leaf # Return Folder3 |
How to take return only the last item inside one path with PowerShell?
1 2 |
$path = 'C:\Folder1\Folder2\Folder3\file.txt' Split-Path -Path $path -Leaf # Return file.txt |
Math
How to arrange write the methods of the System.Math class with PowerShell?
[System.Math] | Get-Member -Static -MemberType Method
How to take return the whole value with PowerShell?
[Math]::Abs(-12) #Returns 12
[Math]::Abs(-12.5) # Returns 12.5
How to take return the angle wey him sine be the ogbonge number with PowerShell?
[Math]::ASin(1) #Returns 1,5707963267949
How to take return the ceiling value with PowerShell?
[Math]::Ceiling(1.4) #Returns 2
[Math]::Ceiling(1.9) #Returns 2
How to take return the floor value with PowerShell?
[Math]::Floor(1.4) #Returns 1
[Math]::Floor(1.9) #Returns 1
How to take return the natural (base e) logarithm of one ogbonge number with PowerShell?
[Math]::Log(4) #Returns 1,38629436111989
How to take return the base 10 logarithm of one ogbonge number with PowerShell?
[Math]::Log10(4) #Returns 0,602059991327962
How to take return the highest of two values with PowerShell?
[Math]::Max(2,4) #Returns 4
[Math]::Max(-2,-4) #Returns -2
How to take return the smallest of two values with PowerShell?
[Math]::Min(2,4) #Returns 2
[Math]::Max(-2,-4) #Returns -4
How to take return one number raised to one ogbonge power with PowerShell?
[Math]::Pow(2,4) #Returns 16
How to take return one decimal value to the nearest small-small value with PowerShell?
[Math]::Round(3.111,2) #Returns 3,11
[Math]::Round(3.999,2) #Returns 4
How to take return the small-small part of a specified decimal number with PowerShell?
[Math]::Truncate(3.111) #Returns 3
[Math]::Truncate(3.999) #Returns 3
How to take return the square root of one ogbonge number with PowerShell?
[Math]::Sqrt(16) #Returns 4
How to take return the PI constant with PowerShell?
[Math]::Pi #Returns 3,14159265358979
How to take return the natural logarithmic base (constant e) with PowerShell?
[Math]::E #Returns 2,71828182845905
How to check wether one number is even or odd with PowerShell?
[bool]($number%2)
Hashtables
How to arrange create one empty hashtable with PowerShell?
$hashtable = @{}
$hashtable = New-Object -TypeName System.Collections.Hashtable
How to arrange create one hashtable with items with 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 |
How to arrange add items (key-value pair) to one hashtable with PowerShell?
$hashtable.Add('Key3', 'Value3')
How to take get one ogbonge value of one hashtable with PowerShell?
$hashtable.Key1
$hashtable.Get_Item('Key1')
How to take get the smallest value of one hashtable with 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 |
How to take get the biggest value of one hashtable with 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 |
How to arrange change items in one hashtable with PowerShell?
$hashtable.Set_Item('Key1', 'Value1Updated')
How to take remove items inside one hashtable with PowerShell?
$hashtable.Remove('Key1')
How to take clear one hashtable with PowerShell?
$hashtable.Clear()
How to take arrange check the presence of one ogbonge key/value inside one hashtable with PowerShell?
$hashtable.ContainsKey('Key3')
$hashtable.ContainsValue('Value3')
How to take arrange key /value inside one hashtable with PowerShell?
$hashtable.GetEnumerator() | Sort-Object -Property Name
$hashtable.GetEnumerator() | Sort-Object -Property Value -Descending
Arrays
How to take create one empty array with PowerShell?
$array = @()
$array = [System.Collections.ArrayList]@()
How to take create one array with items with PowerShell?
$array = @('A', 'B', 'C')
$array = 'A', 'B', 'C'
$array = 'a,b,c'.Split(',')
$array = .{$args} a b c
$array = echo a b c
How to arrange add items to one array with PowerShell?
$array += 'D'
[void]$array.Add('D')
How to takerearrange one item inside one array with PowerShell?
$array[0] = 'Z' # 1st item[0]
How to take check the size of one array with PowerShell?
$array = 'A', 'B', 'C'
$array.Length # Returns 3
How to recollect one item/several/all items inside one array with PowerShell?
$array = @('A', 'B', 'C')
$array[0] # One item (A)
$array[0] + $array[2] # Several items (A,C)
$array # All items (A,B,C)
How to take commot empty things from inside one array with PowerShell?
$array = @('A', 'B', 'C', '')
$array = $array.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object # A,B,C
How to check wether one thing dey for inside array with PowerShell?
$array = @('A', 'B', 'C')
'A' | ForEach-Object -Process {$array.Contains($_)} # Returns True
'D' | ForEach-Object -Process {$array.Contains($_)} # Returns False
How to take look for the index number of one thing inside array with PowerShell?
$array = @('A', 'B', 'C')
[array]::IndexOf($array,'A') # Returns 0
How to take reverse the order of things foritems in an array with PowerShell?
$array = @('A', 'B', 'C')
[array]::Reverse($array) # C,B,A
How to take gather one random things from array with PowerShell?
$array | Get-Random
How to take organise one array inside one ascending/descending way with PowerShell?
$array = @('A', 'B', 'C')
$array | Sort-Object # A,B,C
$array | Sort-Object -Descending # C,B,A
How to take count the number of things inside one array with PowerShell?
$array.Count
How to take add one array to another with PowerShell?
$array1 = 'A', 'B', 'C'
$array2 = 'D', 'E', 'F'
$array3 = $array1 + $array2 # A,B,C,D,E,F
How to look for copo-copy from one array with PowerShell?
$array = 'A', 'B', 'C', 'C'
($array | Group-Object | Where-Object -FilterScript {$_.Count -gt 1}).Values # Returns C
How to take commot copy-copy from one array with PowerShell?
$array = 'A', 'B', 'C', 'C'
$array = $array | Select-Object -Unique
$array # Returns A,B,C
How to take arrange create one array with things starting with one prefix (“user01″,”user02”,… “user10”) with PowerShell?
$array = 1..10 | ForEach-Object -Process { "user$_" }
ACL
How to arrange write ACL of one AD user with PowerShell?
(Get-Acl -Path "AD:\$dn").Access
How to take arrange write ACL of one folder with PowerShell?
(Get-Acl -Path C:\scripts).Access
1 |
((Get-Acl -Path "AD:\$dn").Access | Select-Object -Property IdentityReference | Where-Object -FilterScript {$_.IdentityReference -match 'Admin'} | Get-Unique | ForEach-Object -Process {$_.IdentityReference}).Value |
Variables
Wetin be the most common type of data with 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 |
How to take look for the highest and smallest values for some kind type variables with 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 |
How to take test the kind data wey dey with PowerShell?
1 2 3 |
32 -is [int] $true -is [bool] 'a' -is [string] |
How to take arrange create one Here-String variable with 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} "@ |