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).
December 10th, 2007 at 12:55 pm
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
January 9th, 2008 at 5:19 pm
$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
}
January 20th, 2008 at 6:17 pm
[...] found plenty of help on the web – or at least plenty of suggestions for renaming and batch renaming. But everything I tried gave me [...]
May 11th, 2009 at 11:41 pm
One important thing left off that I can’t found:
cd \windows
dir cmd.exe /s
What is PS’s equivalent?
July 14th, 2009 at 9:31 pm
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?
August 4th, 2009 at 3:52 pm
[...] http://blog.stevex.net/index.php/powershell-cheatsheet/ [...]
August 21st, 2009 at 12:03 am
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:\)
August 21st, 2009 at 12:03 am
Actually, I figure out how to go up a directory, dir .. worked funnily enough!!!
November 19th, 2009 at 9:29 am
Hi Steve,
What if I want to delete directories older than 1 week old?
-Adrian
January 12th, 2010 at 8:52 am
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?
January 26th, 2010 at 10:36 am
Hi,
Is there a command to search for a particular file with todays date in a folder?
February 26th, 2010 at 8:25 am
Get-ChildItem \\omega\test2$\*.txt | % { If (( Get-Content $_) -Match “Test”) { $_ } }
March 3rd, 2010 at 5:27 pm
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.
July 20th, 2010 at 2:35 am
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
September 13th, 2010 at 8:24 am
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”.
October 4th, 2010 at 12:42 am
For the ‘dir /ad’ equivalent, you’ll actually want:
dir |? {$_.PSIsContainer }
(The .MshIsContainer was renamed to .PSIsContainer).
Thanks for the great list!
October 12th, 2010 at 11:19 am
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”
February 15th, 2011 at 5:51 am
Thanks, Ive printed out your sheets as well as techieshelps http://www.techieshelp.com/powershell-commands-and-what-they-do/
April 20th, 2011 at 3:05 pm
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
}
}
April 20th, 2011 at 4:49 pm
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!
April 26th, 2011 at 2:51 pm
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
May 4th, 2011 at 12:51 pm
How can I copy files whose file name contains certain string?
Thanks
June 8th, 2011 at 1:22 am
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
July 13th, 2011 at 9:14 am
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.
September 19th, 2011 at 7:07 am
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 :-)
April 27th, 2012 at 12:22 pm
anyone know the complete Powershell command to set a DESKTOP.INI file permission to Deny for Administrators group?
June 12th, 2012 at 3:31 am
I’m just begining to discover the wonders of Powershell and I would like to thank you very much for this cheat sheet. It has helped me to quickly get started.
September 4th, 2012 at 9:20 pm
hi,
I need a SINGLE directory listing with all three Create Date : Date Accessed and Date modified, Size Attributes just like the window exhibited in Windows.
With Dir I can get only one date at a time (either Create or Accessed or Written)
Is there single line command thru piping whatever to do this.