PowerShell vs Bash

By Xah Lee. Date: . Last updated: .

This pages shows the common tasks in both bash and PowerShell.

Simple Commands

The following bash commands have PowerShell alias. (but the options are not the same)

cdpwdlspushdpopdcprmrmdirmvcatechosetpskillclearman

New File

touch name
ni name

New Directory

mkdir name
mkdir name

Copy Directory

cp -r sourceDir destDir
cp -r sourceDir destDir

Directory Size

# current dir size, in kilo bytes
du . -sk
"{0:N2}" -f ((dir -Recurse | measure -Property Length -sum).sum / 1MB)

find program

which myCommandName
gcm myCommandName

Print File Content

cat fname
cat fname

Print First/Last n Lines of File

head -n 50 fname
cat fname | select -first 50

Print last 50 lines of file

tail -n 50 fname
cat fname | select -last 50

Join Files

cat fname1 fname2 > newFileName
cat fname1, fname2 > newFileName

unzip

unzip fname.zip
Expand-Archive fname.zip

List Files by File Name Extension

find . -name "*html"
dir * -Recurse -include *html

List Backup Files

find . -name "*~"
dir * -Recurse -Include *~

List Directories

find . -type d
dir -Directory -Recurse

List Files Not Directory

find . -type f
dir -File -Recurse

List Empty Files

find . -size 0
dir -recurse | where {$_.length -eq 0}

List Empty Directories

# list empty dir
dir -Directory -Recurse | where { $_.GetFileSystemInfos().Count -eq 0 }

List File Creation Time

# list file with creation time
dir "c:/Users/john/Pictures/ShareX" | sort CreationTime | Format-Table Name, CreationTime
# list files whose creation date is greater than x
dir "c:/Users/john/Pictures/ShareX" | where { $_.CreationTime -gt [datetime]"2014/05/28" } | sort CreationTime | Format-Table Name, CreationTime

delete file

find . -name "*~" -delete
dir * -Recurse -Include *~ | rm

List Files that Contains Search Text

grep myRegex *html
sls *html -pattern myRegex -CaseSensitive

Compare Files

# compare if 2 files are the same. Any binary file
cmp f1 f2
# show difference of 2 text files
diff f1 f2
# compare if 2 files are the same and or show their differences.
diff (cat f1) (cat f2)

diff, sort, get column etc

sort
sort
uniq
sort -Unique
wc
measure

Redirect

# put content in a file
echo "some" > myfile.txt
echo "some more" >> myfile.txt # append
# put content in a file
"some" > myfile.txt
"some more" >> myfile.txt # append

thanks to Jeffrey Snover of Microsoft for helping on about 10 of the items. (Jeffrey's the inventor of PowerShell)

PowerShell

How-to

Advanced

Script Examples