Monday, December 23, 2013

Commonly Used Windows PowerShell Cmdlets

Extract lines from files
Get first 10 lines as head -10 in linux
Get-Content -Path my.csv -TotalCount 10
Get last 10 lines as tail -10 in Linux
Get-Content -Path my.csv | Select-Object -Last 10
Get m-to-n lines:
Get-Content -Path my.csv | Select-Object -Index(10)
Get the 10th to 100th lines
Get-Content -Path my.csv | Select-Object -Index(10..100)
# get 10th and 100th lines
Get-Content -Path my.csv | Select-Object -Index(10, 100)

Search recursively for a certain string within files

Get-ChildItem -Recurse -Filter *.log | Select-String Exception
Get-ChildItem -Recurse -Filter *.log | Select-String -CaseSensitive -Pattern Exception

Tail -f in PowerShell

Get-Content error.log -wait | Where-Object { $_ -match "Exception" } 
-match is case-insensitive. -cmath is case-sensitive.

Find the five processes using the most memory


Get-Process | Sort-Object -Property WS -Descending | Select-Object -First 10

Delete all files within a directory


Remove-Item foldername -Recurse

Using Get-WmiObject

List all WMI classes:
Get-WmiObject -List
Get-WmiObject -Class Win32_ComputerSystem 
Get-WmiObject -Class Win32_BIOS -ComputerName .
gwmi win32_service -filter "name like 'Oracle%'" | select name 
gwmi win32_service -filter "startmode='auto'" | select name,startmode
(gwmi win32_service -filter "name='alerter'").StopService()
Restart the current computer

(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)

Miscs

Rename all .TXT files as .LOG files in the current directory:
Get-Childitem -Path *.txt | rename-item -NewName {$_.name -replace ".txt",".log"}
Restart-Computer –Force –ComputerName TARGETMACHINE
Run a script on a remote computer

invoke-command -computername machine1, machine2 -filepath c:\Script\script.ps1

No comments:

Post a Comment