DEV Community

Cover image for Useful: Powershell Command
Yassine Sellami
Yassine Sellami

Posted on • Updated on

Useful: Powershell Command

  • Helpers
Get-Help Get-Process   // find command info
Get-Command -Name A* -CommandType cmdlet // find all commands installed

Get-ChildItem -Path "C:\Program Files" // find all folders & sub folders
Get-ChildItem -Path "C:\Program Files\java" -Recurse | Select FullName   // find all files 

Set-Location "C:\Users\usrename\Documents" // change current dir
Enter fullscreen mode Exit fullscreen mode
  • OS information
systeminfo.exe /fo csv | ConvertFrom-Csv
Get-ComputerInfo | Select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
(Get-CimInstance Win32_BIOS).SMBIOSBIOSVersion // BIOS Version
(Get-CimInstance Win32_BIOS).SerialNumber      // Serial Number
(Get-CimInstance Win32_ComputerSystem).Model   // Model
Get-CimInstance Win32_Printer | Select-Object Name, PortName, Default   // Printers
(Get-CimInstance Win32_ComputerSystem).Domain  // AD Domain

(Get-CimInstance Win32_OperatingSystem).LastBootUpTime // Time of the Last Reboot

(Get-PSDrive $Env:SystemDrive.Trim(':')).Free/1GB  //Get Free Space for System Drive
Enter fullscreen mode Exit fullscreen mode
  • IO
---# Copy & Move
Copy-Item "D:\myFolder1" -Destination "D:\myFolder2" -Recurse // Copy-paste files and folders

Move-Item -Path "E:\Folder1" -Destination "E:\Folder2"  // move folder

Remove-Item E:\Folder1\myFile.txt // remove file

---# Content
// Set content 
Set-Content -Path .\myFile.txt -Value 'This is content...'

// Get file content
Get-Content -Path .\myFile.txt
// Get content of all *.log files in the C:\myDir directory 
Get-Content -Path C:\myDir\* -Filter *.log

Get-Content ./myFile.log -Tail 5 –Wait  // follow a File 

Get-Content -Path .\myFile.txt -TotalCount 5  // first 5 lines
(Get-Content -Path .\myFile.txt -TotalCount 25)[-1]  // return the line 25
Get-Item -Path .\myFile.txt | Get-Content -Tail 1  // last line
Get-Content -Path .\myFile.txt -Raw     // get as one string
(Get-Content -Path .\myFile.txt).Count  // Count lines

Clear-Content -Path "E:\myFile.txt" // delete the contents of the file without deleting the file

Get-ChildItem -Directory  // List Subdir in the Current Directory

---# Zip / Unzip
Compress-Archive -Path "C:\myDir\*.log" -DestinationPath "C:\"
Compress-Archive -LiteralPath "C:\myDir\file1.txt","C:\myDir\file2.txt" -DestinationPath "C:\"

Expand-Archive -LiteralPath "C:\" -DestinationPath "C:\myDir2"

Enter fullscreen mode Exit fullscreen mode
  • Services
Get-Process            // listing all active system processes
Start-Process notepad  // start process
Get-Service -Name "Win*"  // find services
Get-Service | Where-Object {$_.status -eq "Started"}  // List Started Services 

Enter fullscreen mode Exit fullscreen mode
  • Network
---# Test & diagnostic
// Sends ICMP echo req, or pings, to one or more computers
Test-Connection -TargetName Server01 -IPv4
Test-Connection -TargetName Server01, Server02, Server12
Test-Connection -TargetName -Traceroute  // PowerShell 6.0

// Displays diagnostic info for a connection
Test-NetConnection -Port 80 -InformationLevel "Detailed"   // locally
Test-NetConnection -ComputerName "" -InformationLevel "Detailed" // remotly

---# Find & listing
(Invoke-RestMethod // Your Public IP

// find all listening & established connections
netstat -a
Get-NetTCPConnection -State Listen
// Process listening on a TCP 
Get-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess
// Process listening on a UDP 
Get-Process -Id (Get-NetUDPEndpoint -LocalPort 53).OwningProcess

---# Network information
Get-NetAdapter      // Gets network adapter properties.
Restart-NetAdapter  // Restarts network adapter.
Get-NetIPAddress    // Gets the IP address configuration.
// Gets an IP interface
Get-NetIPInterface | Format-Table
// Gets IP route info from IP routing table.
Get-NetRoute | Format-List -Property *
Enter fullscreen mode Exit fullscreen mode
  • HTTP Call
Invoke-WebRequest -Uri "" -UseBasicParsing | Select-Object -ExpandProperty 'Content' | ConvertFrom-Json

Invoke-RestMethod "" | Select-Object id,title | Format-List

Enter fullscreen mode Exit fullscreen mode
  • History
---# Displays session's history
// Path history file
(Get-PSReadlineOption).HistorySavePath  // get
Set-PSReadlineOption –HistorySavePath C:\Temp\NewHistory.txt  // update

---# Add / Append
// Add / import history of a different session
Get-History | Export-Csv c:\Tmp\history.csv -IncludeTypeInformation
Import-Csv c:\Tmp\history.csv | Add-History

---# Delete history
Clear-History -Count 5 -Newest
Remove-Item (Get-PSReadlineOption).HistorySavePath // clear history
Clear-History -CommandLine *Help*, *Syntax  // match criteria
Clear-History -Id 3, 5

Enter fullscreen mode Exit fullscreen mode
  • DNS
---# DNS query resolution
// Performs a DNS query resolution for the specified name
Resolve-DnsName -Name
Resolve-DnsName -Name -Server  // Against DNS server at
Resolve-DnsName -Name -Type A   // queries for A type records
Resolve-DnsName -Name -DnsOnly  // only DNS, LLMNR & NetBIOS queries are not issued
Resolve-DnsName -Name -Type A -Server localhost -DnssecOk

---#  DNS client cache
// Contents of DNS client cache.
Get-DnsClientCache -Entry

Enter fullscreen mode Exit fullscreen mode
  • NTP (Windows Time service)
w32tm /stripchart /computer:<SERVER> /dataonly /samples:5 //check
w32tm /query /peers   // listing
w32tm /query /status  // check current ntp config
w32tm /query /configuration   // show config (MUST Admin)

-- Restore config
net stop w32time
w32tm /unregister
w32tm /register
net start w32time

function Test-NTP($ntpserver){
   $pinfo.RedirectStandardOutput = $true
   $pinfo.UseShellExecute = $false
   return $ntptestproc.StandardOutput.ReadToEnd() -match ",\ (\+|-)0"

Enter fullscreen mode Exit fullscreen mode
  • ADFS
---# ADFS Properties
// Get properties
Get-AdfsProperties | fl "autocertificaterollover"
// Set properties
Set-AdfsProperties -AutoCertificateRollover $true       //
Set-ADFSProperties -EnableIdPInitiatedSignonPage:$true  //

---# Http headers
Set-AdfsResponseHeaders -EnableCORS $true    // Enable http CORS header
Set-AdfsResponseHeaders -CORSTrustedOrigins https://,http/..  

---# Theming
Set-AdfsWebTheme -TargetName default -Logo @{path="c:\myTheme\logo.png"}
Set-AdfsGlobalWebContent –CompanyName "My Company"

Enter fullscreen mode Exit fullscreen mode
  • Security
---# HotFix
Get-HotFix // Get all hotfixes on the local computer
Get-HotFix -Id KB957095
Get-HotFix -Description Security* -ComputerName SRV1, SRV2 -Credential MyDomain\myUserAdmin //Get hotfixes from multiple computers filtered by a string, with cred myUserAdmin that has permission to access the remote computers and run commands.

// Verify whether a particular update installed:
$SRV = Get-Content -Path ./Servers.txt
$A | ForEach-Object { if (!(Get-HotFix -Id KB957095 -ComputerName $_))
         { Add-Content $_ -Path ./Missing-KB957095.txt }}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)