PowerShell Cheatsheet

PowerShell is Microsoft’s replacement for cmd.exe, the venerable NT command shell. It breaks new ground, introducing a powerful but completely new syntax. (If you don’t have it yet, download it here).

Revolutionary but different, users new to PowerShell will often find themselves lost – not being able to figure out how to do simple things that they’ve been doing in other shells for the last 20 years. This cheat sheet should help.

PowerShell’s native commands are all based on a verb-noun syntax, for example, "get-childitem". Command names are often quite verbose, so there is an extensive list of default aliases that help with common commands. The table below will give the alias, where available, as well as the native PowerShell command.

Operation cmd PowerShell
Get a simple directory listing
dir
get-childitem
alias: dir
Get a recursive directory listing
dir /s 
get-childitem -recurse
alias: dir -r  
Get a wide directory list
dir /w 
dir | format-wide
alias: dir | fw 
List built-in commands
help
get-command
alias: help
Copy a file
copy foo.txt bar.txt 
copy-item foo.txt bar.txt
alias: copy foo.txt bar.txt 
Move a file
move foo.txt c:\ 
move-item foo.txt d:\
alias: move foo.txt d:\ 
Rename a file
ren foo.txt bar.txt 
rename-item foo.txt bar.txt
alias: ren foo.txt bar.txt 
Batch rename
ren *.one *.two
dir *.pdf | rename
  -newname {$_.name -rep ".one",".two"}
Set the current directory to d:\
d:
cd \ 
set-location d:\
alias: cd d:\ 
Clear the screen
cls
clear-host
alias: cls
List only directories
dir /ad 
dir | where { $_.MshIsContainer }
Directory list, sorted by date
dir /od 
dir | sort-object LastWriteTime
Directory list, sorted by date, descending order
dir /o-d 
dir | sort-object LastWriteTime -desc
Show the current directory
cd
get-location
alias: pwd
See a command’s help
dir /? 
get-help get-command
or: get-help get-command -detailed
or: get-help get-command -full
or: dir -? 
List environment variables
set
dir env: 
Delete a file
del foo.txt 
remove-item foo.txt
alias: del foo.txt 
Find all *.txt files
dir /s *.txt 
get-childitem -recurse -include *.txt
alias: dir -r -i *.txt 
Find all *.txt files containing a particular string
findstr "foo" *.txt
dir *.txt | select-string "foo" 
Show a list of services
net start 
get-service
Start a service
net start MyService
start-service MyService 
Stop a service
net stop MyService 
stop-service MyService 
Show network shares
net share
gwmi Win32_Share 
Show a list of running processes
tasklist
get-process alias: ps 
Kill all notepad.exe processes
taskkill /im notepad.exe /f 
ps notepad | kill 

A few PowerShell commands that you can’t easily do with the standard Windows shell:

Operation PowerShell
Set the current directory to a UNC path
cd \\\\myserver\\\myshare 
Get a list of event logs
get-eventlog -list 
View entries in a particular event log
get-eventlog -newest 20 -logname System 
Treat the registry like a filesystem
cd hkcu:
dir
Recursive directory, grouped by extension
dir -r | group extension 
Search for a file containing a string, recursive
dir -r | select-string "foo" 
List the 10 processes using the most memory
ps | sort -p ws | select -last 10
Count the results of a directory listing
(dir).count
Count the results of a directory listing
$f = Get-Content "myfile.txt"
foreach ($item in $f)
{do stuff with $item}

There’s a lot to PowerShell, and this only scratches the surface. This guide is meant to help you get going with some everyday commands, but be sure to read some of these great PowerShell blogs, and the PowerShell Script Center for more in-depth tips. (And here’s a good reference on PowerShell syntax).

25 Responses to “PowerShell Cheatsheet”

  1. james stokes Says:

    What i would like to do is:
    1- set a variable with string of the directory we want to use
    2- set a filename of outfile.sql
    2- gather the content of all files with the extension of “*.sql” merge into outfile.txt

  2. Steinam Says:

    $directory = “C:\sql”
    $output = “C:\outfile.sql”

    #ErrorAction enum if File does not exist
    Clear-Content $output -ErrorAction “SilentlyContinue”

    $list = Get-ChildItem -Path $directory -Filter *.sql
    foreach ($i in $list)
    {
    $a = get-content $i.FullName
    add-Content $a -Path $output
    Add-Content “– ========== next sql –” -Path $output
    }

  3. Mike Ormond's Blog : Powershell Batch Rename Says:

    [...] found plenty of help on the web – or at least plenty of suggestions for renaming and batch renaming. But everything I tried gave me [...]

  4. mycall Says:

    One important thing left off that I can’t found:

    cd \windows
    dir cmd.exe /s

    What is PS’s equivalent?

  5. Jon Saxton Says:

    I note that PS honours my UI setting for date format (YYYY-MM-DD) in directory listings but it insists on using am/pm for file modification times even though I have told Windows to use a 24-hr clock. So far I have not figured out a workaround for that. Given that the date works, could this be a bug or an oversight?

  6. PowerShell Cheat Sheet - InterVirt Says:

    [...] http://blog.stevex.net/index.php/powershell-cheatsheet/ [...]

  7. Jayson Gabler Says:

    Does anyone know to:

    dir .. (go up one directory)
    output the name of a directory to a variable that can be used for comparison
    Detect when you’ve reached the end of a directory tree, i.e. C:\Dir1\Dir2\Dir3 (stop at Dir3)
    Detect when you’ve reached the start of a directory tree, i.e. C:\Dir1\Dir2\Dir3 (stop at C:\)

  8. Jayson Gabler Says:

    Actually, I figure out how to go up a directory, dir .. worked funnily enough!!!

  9. Adrian Rodriguez Says:

    Hi Steve,

    What if I want to delete directories older than 1 week old?

    -Adrian

  10. Niklas E Says:

    Anyone with a command that can give me a list of all files that do NOT contain SUCCESS inside the text file for all result.txt files under C:\batches\* (recursive subfolders) . Since all files have same name, but are in separate folder, I guess I need full path name as well. I have been able to do the reverse to find all that contain SUCCESS, but not the ones that do not contain it.

    get-childitem C:\batches\* -include result.txt -recurse | select-string -pattern “SUCCESS” -list | Select-Object Path

    I also tried NotMatch but it didn’t work as it finds all files as there are rows within the files that don’t have that line.

    Any ideas?

  11. Jickson sebastian Says:

    Hi,

    Is there a command to search for a particular file with todays date in a folder?

  12. Mischa Says:

    Get-ChildItem \\omega\test2$\*.txt | % { If (( Get-Content $_) -Match “Test”) { $_ } }

  13. Justin Says:

    Update on Mischa’s script:

    Get-ChildItem C:\batches -include result.txt -recurse |? { -not $($(Get-Content $_) -match “SUCCESS”) }

    “|?” is a short-cut for “| Where-Item”, which is basically what the for-each command Mischa wrote is doing.

  14. Reidar Says:

    Is there a way to do a batch rename of files to add their current directory to the file name?

    Here what I have
    c:\files\norway\file1.txt
    c:\files\norway\file2.txt
    c:\files\norway\file3.txt
    c:\files\sweden\file1.txt
    c:\files\sweden\file2.txt
    c:\files\sweden\file3.txt

    Here’s what I want:
    c:\files\norway\norwayfile1.txt
    c:\files\norway\norwayfile2.txt
    c:\files\norway\norwayfile3.txt
    c:\files\sweden\swedenfile1.txt
    c:\files\sweden\swedenfile2.txt
    c:\files\sweden\swedenfile3.txt

    The purpose is to be able to move these files to a single directory without causing file name conflict, and I’d like to be able to batch the rename of the files (the subsequent move is easy).

    Thanks,
    Reidar

  15. Stephen Says:

    For the batch file rename I find I have to do this instead of what is mentioned here :

    dir *.pql | rename-item -newname {$_.name -replace “.pql”,”.sql”}

    Instead of “rename”, I have to use “rename-item” (which can just be shortened to “ren”).
    Instead of the shortened “rep” I have to use the full “replace”.

  16. JarrodN Says:

    For the ‘dir /ad’ equivalent, you’ll actually want:
    dir |? {$_.PSIsContainer }

    (The .MshIsContainer was renamed to .PSIsContainer).

    Thanks for the great list!

  17. Paul M. Parks Says:

    Why are the backslashes escaped (incorrectly, I might add) in the example on how to change directory to a UNC path? “cd \\server\share” works fine on my Powershell 2.0 installation (I haven’t tried 1.0). Forward slashes work just as well, too: “cd //server/share”

  18. Allen White Says:

    Thanks, Ive printed out your sheets as well as techieshelps http://www.techieshelp.com/powershell-commands-and-what-they-do/

  19. Jen Says:

    How can I grab the files with the lowest number in in the file name from a directory. (date/time is same). This is kind of what i was trying to do, but i am receive error i’m trying to perform a method on a null value. This is the line that isn’t working I think: i$ = (Get-ChildItem -Name “d:\pmta\logtemp\acct*.csv” | Sort-Object $i.Substring(17,4) -ascending | select-object -first 1)

    Complete Script (runs a command, then grabs the file in the directory with the lowest number in it’s file name to perform actions on):

    if (!(Test-Path -path d:\pmta\logprocessing\*))
    {
    $files = (Get-ChildItem -Name “d:\pmta\logtemp\acct*.csv”)
    if ($files.count -lt 1)
    {
    invoke-expression “d:\pmta\bin\pmta rotate acct” | out-null
    }

    #foreach ($i in Get-ChildItem -Name “d:\pmta\logtemp\acct*.csv” )
    i$ = (Get-ChildItem -Name “d:\pmta\logtemp\acct*.csv” | Sort-Object $i.Substring(17,4) -ascending | select-object -first 1)
    {

    Move-Item d:\pmta\logtemp\$i d:\pmta\logprocessing
    Copy-Item d:\pmta\logprocessing\$i d:\pmta\logarchive\
    Get-Content d:\pmta\logprocessing\$i | where { $_ -notmatch “cold” } | Add-Content -path d:\pmta\log\$i
    Remove-Item d:\pmta\logprocessing\$i
    }
    }

  20. Jen Says:

    I figured the answer to my own question. I changed the line in question to foreach ($i in Get-ChildItem -Name “d:\pmta\logtemp\acct*.csv”| Sort-Object | Select-Object -first 1).

    Thanks folks!

  21. jim manning Says:

    Hi:

    I need powershell to return a value on multiple identities in one command:

    like: get-mailbox -id jim.jones; bob.smith; peter.johnson | select linkedmasteraccount

  22. Ran Says:

    How can I copy files whose file name contains certain string?

    Thanks

  23. chilun Says:

    Hi;

    I need help with time stamping. I’d like to also add the time and time along with the $computer variable (each line). Can anyone help me?

    Here is a line of my code:

    $computer | Out-File C:\VNCRestarted.txt -Append

  24. Rich Says:

    I like a powershell script to do the following:

    Grab all files in c:\abc\a123 and c:\abcb123 which has today’s date and move to new folder c:\cba\xyz with “YD_” added to the beginning of each file name.

    At the end, I like powershell to write an event to eventviewer indicating when the event was last successfully ran.
    Additionally, if would be a great idea to email to Rich@abc.com that the job successfully ran with date and time stamped.

  25. tramper42 Says:

    under win server 2008 r2 (others maybe after updating)

    # set date to year-month-day
    $today = Get-Date -uFormat “%Y-%m-%d”
    echo $today

    copy all files: ROBOCOPY /e/s \\server1\c$\data\ \\server2\c$\databackup\ever\
    synch all files: ROBOCOPY /mir \\server1\c$\user\Joe\\ \\server2\c$\databackup\user\Joe\
    move all files: ROBOCOPY /move \\server1\c$\todaysTempWork\ \\server2\c$\databackup\$today\

    robocopy will start also in powershell :-)

Leave a Reply

buy cheap Endep online buy cheapest Endep and Endep how to order Amitriptyline online without prescription buy Amitriptyline without rx from us pharmacy online Amitriptyline purchase purchase online prescription Amitriptyline without purchasing Amitriptyline online without prescription order generic Amitriptyline buy Endep no prescriptions how to order Endep online without prescription comprare Endep generico Endep online buy Endep in england buy cheap Endep online free consult Endep purchased online without prescription what is Endep Endep tabletten buy Endep no perscription cod Endep non rx fedex overnight free want to buy Anafranil in usa Aricept overdose buy discount Aricept on line Aricept buy Aricept online Aricept order buy Aricept pills Nizoral suppliers cheap order rx Nizoral canada Nizoral order Nizoral usa cod comprar Nizoral generico buy Nizoral 200 mg buy cheap Nizoral under without rx buy cheap Nizoral with dr. prescription Prozac 200 mg buy Lisinopril australia el Nizoral generico buy Lisinopril tablets without rx next day delivery Lisinopril with no script buy Lisinopril c o d purchase arimidex no scams order Arimidex order amex Arimidex canadian pharmacy buy Arimidex without doctor order rx free Arimidex buy Abilify with american express buy Abilify cod where can i purchase Abilify without a prescription order Finpecia without a prescription cheap order rx Finpecia purchase Famvir no visa online without prescription buy Famvir paypal without rx buy Famvir without Famvir without prescription medications Famvir without persription purchase Famvir online no membership overnight shipping Famvir no physician approval Amitriptyline purchase order Amitriptyline free next day airAmitriptyline on line buy next day Fluoxetine buy Fluoxetine line purchase Fluoxetine cod delivery buy Fluoxetine 20 mg purchase Fluoxetine buy cheap Fluoxetine under without rx purchase Fluoxetine visa without prescription Fluoxetine by mail Fluoxetine for pets Fluoxetine 10mg Amitriptyline purchase online how to order Famvir online without a rx Prozac Amitriptyline no perscription Famvir next day purchase Anafranil no prescription cheap buy cheapest Anafranil next day delivery on Anafranil saturday Anafranil buy Anafranil buy Anafranil overnight where to purchase Anafranil no prescription no fees Anafranil drug buy Lisinopril where Lisinopril buy on line order Lisinopril online no membership overnight shipping no prescription required for Lisinopril order maxalt cash on delivery Maxalt from canada buy cheapest Maxalt purchase Maxalt visa without prescription buy Maxalt uk Maxalt 10 mg purchase Maxalt no visa online without prescription purchase generic Lisinopril online Lisinopril no prescription to buy maxalt order online no membership overnight how to get a arimidex rx Aricept without a perscription fedex Aricept overnight without a prescription Donepezil prescription order buy genuine Aricept Aricept uk sales buy Amitriptyline with amex Accutane 40 mg delivered overnight buy brand Accutane 40 mg Accutane 40 mg orderd online without prescription where to purchase generic Accutane 40 mg online without a rx how to get 40 mg Accutane without next day delivery 40 mg Accutane with no script buy Amitriptyline online Accutane 40 mg online no prescription buy Accutane 40 mg online us pharmacy Accutane 40 mg best buy buy Accutane 40 mg c o d order 40 mg Accutane cash on delivery no presciption 40 mg Accutane