Bash To Powershell Cheat Sheet



On August 18, 2016, Microsoft announced that PowerShell was going open source and provided its source code to the public, adding support to Unix-based OSes, including Linux distros and OS X. SEE: All of TechRepublic's cheat sheets and smart person's guides (TechRepublic) PowerShell 7 is the newest version of PowerShell and serves as a.

  • PowerShell: Variables Cheat Sheet. Initialize a variable. int $a = 'Trevor'. Initialize a variable, with the specified type (throws an exception) string $a = 'Trevor'. Initialize a variable, with the specified type (doesn’t throw an exception) Get-Command -Name.varia.
  • PowerShell was developed more than 10 years ago by Microsoft to expand the power of its command line interface (CLI) by coupling it with a management framework that is used to manage local.
  • Bash to PowerShell Cheat Sheet While Tom was learning PowerShell, he found himself trying to translate the bash commands he was familiar with into the PowerShell commands that accomplish the same task, coming up with this handy cheat sheet.
  • Image: Microsoft. PowerShell was developed more than 10 years ago by Microsoft to expand the power of its command line interface (CLI) by coupling it with a management framework that is used to manage local and remote Windows, macOS, and Linux systems.

The majority of my colleagues have more of a Linux background than Windows. So their cat and their grep are near and dear to their heart and their first reflex when they get into PowerShell is to replicate these commands.

First, this is not always a good approach because bash and PowerShell are fundamentally different. When we run bash commands or external executables in bash, we get plain text. When we run PowerShell cmdlets we get objects.
So quite often, translating the bash way of doing things to PowerShell is the bad way of doing things. Powershell gives us rich objects with properties and methods to easily extract the information we need and/or to manipulate them in all sorts of ways. Use this to your advantage !

Still, I’m going to do this translation exercise for a few basic commands because it can be an interesting learning exercise for bash users coming to PowerShell. Besides, this is an opportunity to illustrate fundamental differences between bash and PowerShell.

pwd :

Get-Location
Here is an example :

By the way, PowerShell has been designed to be user-friendly, even old-school-Unix-shell-user-friendly, so there are built-in aliases for popular Linux/bash commands which are pointing to the actual cmdlet.
For example, bash users can still let their muscle memory type pwd, because it is an alias to the cmdlet Get-Location. Other alias to this cmdlet : gl.

cd :

Set-Location
But you can use the aliases cd, sl or chdir if you have old habits or to save typing when you are using PowerShell interactively at the console.

ls :

Get-ChildItem
Conveniently, there is the built-in ls alias for those who come from bash and dir for those who come from cmd.exe.
A parameter combination which is frequently used is ls -ltr, it sorts the items to get the most recently modified files at the end.The PowerShell equivalent would be :

Notice how close to plain English the syntax is. This helps you “Think it, type it, get it” as Jeffrey Snover likes to say.
Sorting is based on a property, not a column, so you don’t need to know the column number, you just need the property name.

find :

Get-ChildItem
But this time with the Include (or Filter) and Recurse parameters.For example, a common use case of find is to look recursively for files which have a case-insensitive string in their name :

PowerShell is case-insensitive in general, so we have nothing in particular to do in this regard :

Sheet

cp :

Copy-Item
Let’s say you want to copy a folder named Tools including all its files and sub-directories to your home directory, in bash you run :

In PowerShell on a Windows machine, you would run :

$env: is a scope modifier, it tells PowerShell to look for the variable named USERPROFILE in a special scope : the environment. This is a convenient way to use environment variables.

In addition, the Path and Destination parameters are positional. Path is at position 1 and Destination is at position 2, so the following command accomplishes the same as the previous one :

To save even more typing, we could use the aliases cp, copy or cpi.

rm :

Remove-Item
Here is the equivalent of the (in)famous rm -rf :

And if you tell me it’s too much typing, I’m going to throw aliases at you :
rm, ri, rmdir, rd and del.

mkdir :

It does create the parent if needed without any special parameter, so it works like mkdir -p as well.

touch :

New-Item
For those who like to “touch” to create a bunch of files, the cmdlet New-Item can do it when specifying ‘File’ for the ItemType parameter.A nice usage example is :

This creates 4 files : Myfile1, Myfile2, Myfile3 and Myfile4.
Here is a simple way to do this with PowerShell :

This deserves a few explanations.
.. is the range operator, so 1..4 stands for 1,2,3,4.
ForEach-Object is a cmdlet used for iteration. It executes the scriptblock between the {} once for every object passed to it via the pipeline.

In case you are wondering what is the $_ in the example above, it is a representation of the object currently being processed, which was passed from the pipeline. So, in the example above, $_ stores the value 1, then it stores the value 2, then the value 3 and finally the value 4.

cat :

Get-Content
Note that even when we run this cmdlet against a text file, this doesn’t output plain text, this outputs one object of the type [string] for each line in the file.
we can use its aliases : cat, gc or type.

tail :

This would output the last 7 lines of the file MyFile1 :

The Tail parameter has an alias : Last, this makes this parameter more discoverable for those who Tail would not even cross their mind because they don’t have a Linux background. This parameter was introduced with PowerShell 3.0.

An exceedingly valuable usage of the tail command for troubleshooting is tail -f to display any new lines of a log file as they are written to the file. For this, there is the Wait parameter, which was introduced in PowerShell 3.0 as well.

grep :

This is the one I get asked about the most :

“How do you do ‘grep’ in Powershell ?”

And my answer is :

Powershell Script Cheat Sheet

“Most of the time, you don’t.”

Think about what you are trying to achieve when you use grep : filtering lines of text which contain a specific value, string, or pattern.

In Powershell, most of the time we are dealing with objects so this translates to : filtering the objects which have 1 or more value(s) in a property.No text-parsing required here, unless you are dealing with objects of the type [string].

Bash To Powershell Cheat Sheet

Many cmdlets have built-in parameters which allows to filter the objects, but the generic filtering mechanism is the cmdlet Where-Object.For example, to filter the processes which have a working set of more than 100 MB, you would run the following :

Notice that in the output, the WorkingSet property is displayed in KiloBytes, but this is due to the formatting view, the actual value is in bytes.

Since PowerShell version 3.0, Where-Object supports a simplified syntax, so the following would do the same as the previous command :

By the way, in case we are dealing with strings and we really want to filter objects on a specific string or pattern, we can use Select-String.
One use case is working with a plain text log file, for example :

And if you are a regular expression nerd, you can feed them to the Pattern parameter.

uname :

For example, uname -a outputs the OS, the hostname, the kernel version and the architecture.
A good way to get the equivalent information on a Windows machine with PowerShell is to use the Win32_OperatingSystem class from CIM/WMI :

Yes, I know, it is much longer. Fortunately, there is tab completion for cmdlets, parameters, and even sometimes for parameter values.
The Format-Table -AutoSize is just to make the width of the output blog-friendly.

Bash To Powershell Cheat Sheet Examples

mkfs :

Powershell basic cheat sheet

New-Volume or Format-Volume if the volume already exists.

Powershell Cheat Sheet Pdf

ping :

Off course, we could run ping.exe from PowerShell but if we need an object-oriented ping equivalent, there is the cmdlet Test-Connection :

man :

Bash To Powershell Cheat Sheet

Get-Help
The PowerShell help system is extremely… helpful and it would deserve an entire article on its own.
To get the help information for a specific cmdlet, let’s say Stop-Service :

The parameter Full outputs everything : the description, syntax, information on every parameter, usage examples…
We can also search help information on conceptual topics. Let’s say you are a regular expression nerd and you want to know how they work :

Bash To Powershell Cheat Sheet Download

The help files for conceptual topics have a name starting with “about_”.

cut :

This is used to select columns from a text input (usually a file).
Because this is plain text, we need to map the fields to the column numbers and depending on the format of the input we may need to specify a delimiter to define the columns.

In PowerShell, this painful text-parsing is not required because again, we deal with objects.
If you want to retain only some properties from some input objects, just use Select-Object and specify the property names.
That’s it.

The quotes surrounding the property names are not mandatory. They indicate that these are [string] values but because the Property parameter of Select-Object expects strings, PowerShell is kind enough to cast (convert) these values to strings.

Bash To Powershell Cheat Sheet Example

There are plenty of other commands and I cannot write on all of them, but if there are popular commands that you think should be there, please let me know and I will add them to this article.

Because we’re not “sexists”, here’s some common and usefull Bash to PS equivalents. Yes, *nixes pussies, you can now start to use Windows! 😉

Bash commandPowerShell EquivalentExplanation
man xxxGet-Help xxx –fullDisplays the help for the ‘xxx’ command
chmod 123 xxx$ACL = Get-Acl xxx
$TempACL = New-Object SSAF1
$ACL.SetAccessRule($TempACL)
Set-Acl XXX $Acl
Modifys Access Control Lists (ACLs) for the ‘xxx’ file
pwdGet-LocationDisplays the name of the current directory
cd xxxSet-Location xxxChanges the current directory for the ‘xxx’ directory
cp xxx PATHCopy-Item xxx PATHCopies the ‘xxx’ files to another location (‘PATH’)
clearClear-HostClears the screen
rm xxx yyyRemove-Item xxx yyyDeletes the ‘xxx’ and ‘yyy’ files
rm -rfi xxx yyyRemove-Item xxx yyy –Force –Recurse -ConfirmDeletes the ‘xxx’ and ‘yyy’ files from all subdirectories, even if it’s read-only files. Ask for confirmation for each file
lsGet-ChildItemDisplays a list of files and subdirectories in a directory
ls -RGet-ChildItem -RecurseDisplays files in specified directory and all subdirectories
ls -dGet-ChildItem | Where {$_.PSIsContainer}Displays files with specified attributes, directories only
diff file1 file2Compare-Object $(Get-Content File1) $(Get-Content File2)Compares two files and displays the differences between them
grep “xxx” yyySelect-String -Pattern xxx -Path yyySearch for the ‘xxx’ string in the ‘yyy’ file and display the line(s) number(s) if found
uname -n$env:computernameDisplays the computer’s hostname
smbclient -L localhostGet-WmiObject Win32_ShareGets the current network and administrative shares
dateGet-DateGets the current date and time
PATHTO/xxx startStart-Service xxxStarts the ‘xxx’ service
mv xxx yyyRename-Item xxx yyyRename a file
envGet-ChildItem env:Displays CMD environment variables
set x=Clear-Item $xDeletes the contents of the ‘x’/’$x’ variable
set x=value$x=valueAffect ‘value’ to the ‘x’/’$x’ variable
.xxxInvoke-Item xxxInvoke the (provider-specific) default action on the ‘xxx’ item
psGet-ProcessGets the processes that are running on the local computer or a remote computer

To Be Enriched…


1 SSAF: System.Security.AccessControl.FileSystemAccessRule(“user”,”FullControl”,”Allow”)


PS Fab:>Get-RelatedPosts

Powershell Command Cheat Sheet Printable

    # PowerShell CheatSheet – Aliases
    # PowerShell CheatSheet – Automatic Variables
    # PowerShell CheatSheet – Function Keys
    # PowerShell CheatSheet – CMD > PS