Introduction to PowerShell for Unix
people
PowerShell.org
Introduction to PowerShell for Unix peo-
ple
PowerShell.org
This project can be followed at:
https://www.penflip.com/powershellorg/a-unix-persons-guide-to-powershell
©2015 PowerShell.org
Contents
3
1 About
Principal author: Matt Penny
This e-book is intended as a ‘Quick Start’ guide to PowerShell for people who already know Bash or
one of the other Unix shells.
The book has 3 elements:
• an introductory chapter which covers some PowerShell concepts
• a summary list of PowerShell equivalents of Unix commands in one e-book chapter
• a detailed discussion of Powershell equivalents of Unix commands, organised in the alphabetical
order of the unix command
Visit www.penflip.com/powershellorg to check for newer editions of this e-book.
This guide is released under the Creative Commons Attribution-NoDerivs 3.0 Unported License. The
authors encourage you to redistribute this file as widely as possible, but ask that you do not modify
the document.
PowerShell.org eBooks are works-in-progress, and many are curated by members of the com-
munity. We encourage you to check back for new editions at least twice a year, by visiting
www.penflip.com/powershellorg.
You can download this book in a number of different formats (including EPUB, PDF, Microsoft
Word and Plain Text) by clicking Download on the right side of the page.
PDF Users: Penflip’s PDF export often doesn’t include the entire ebook content. We’ve reported
this problem to them; in the meantime, please consider using a different format, such as EPUB,
when you’re downloading the book.
You may register to make corrections, contributions, and other changes to the text - we welcome
your contributions! However, we recommend you check out our contributor tips and notes before
jumping in.
You may also subscribe to our monthly e-mail TechLetter for notifications of updated e-book editions.
Visit PowerShell.org for more information on the newsletter.
4
2 Introduction to PowerShell for Unix
people
The point of this section is to outline a few areas which I think *nix people should pay particular
attention to when learning Powershell.
Resources for learning PowerShell
A full introduction to PowerShell is beyond the scope of this e-book. My recommendations for an
end-to-end view of PowerShell are:
• Learn Windows PowerShell in a Month of Lunches - Written by powershell.org’s Don Jones
and Jeffery Hicks, I would guess that this is the book that most people have used to learn
Powershell. It’s ‘the Llama book’ of Powershell.
• Microsoft Virtual Academy’s ‘Getting Started with PowerShell’ and ‘Advanced Tools & Script-
ing with PowerShell’ Jump Start courses - these are recordings of day long webcasts, and are
both free.
unix-like aliases
PowerShell is a friendly environment for Unix people to work in. Many of the concepts are similar,
and the PowerShell team have built in a number of Powershell aliases that look like unix commands.
So, you can, for example type:
1 ls
….and get this:
1 Directory : C:\ temp
2 Mode LastWriteTime Length Name
3 ---- ------------- ------ ----
4 -a--- 22/02/2015 16:51 25773 all_the_details .md
5 -a--- 20/02/2015 07:31 3390 commands - summary .md
5
6
These can be quite useful when you’re switching between shells, although I found that it can be
irritating when the ‘muscle-memory’ kicks in and you find yourself typing ls -ltr in PowerShell and
get an error. The ‘ls’ is just an alias for the PowerShell get-childitem and the Powershell command
doesn’t understand -ltr[1].
the pipeline
The PowerShell pipeline is much the same as the Bash shell pipeline. The output of one command
is piped to another one with the ‘|’ symbol.
The big difference between piping in the two shells is that in the unix shells you are piping text,
whereas in PowerShell you are piping objects.
This sounds like it’s going to be a big deal, but it’s not really.
In practice, if you wanted to get a list of process names, in bash you might do this:
1 ps -ef | cut -c 49 -70
…whereas In PowerShell you would do this:
1 get - process | select ProcessName
In Bash you are working with characters, or tab-delimited fields. In PowerShell you work with field
names, which are known as ‘properties’.
get-help, get-command, get-member
get-member
When you run a PowerShell command, such as get-history only a subset of the get-history output
is returned to the screen.
In the case of get-history, by default two properties are shown - ‘Id’ and ‘Commandline’…
1 $ get - history
2
3 Id CommandLine
4 -- -----------
5 1 dir -recurse c:\ temp
…but get-history has 4 other properties which you might or might not be interested in:
1 $ get - history | select *
2
3 Id : 1
4 CommandLine : dir -recurse c:\ temp
5 ExecutionStatus : Completed
6 StartExecutionTime : 06/05/2015 13:46:56
7 EndExecutionTime : 06/05/2015 13:47:07
7
The disparity between what is shown and what is available is even greater for more complex entities
like ‘process’. By default get-process shows 8 columns, but there are actually over 50 properties (as
well as 20 or so methods) available.
The full range of what you can return from a PowerShell command is given by the get-member
command[2].
To run get-member, you pipe the output of the command you’re interested in to it, for example:
1 get - process | get - member
….or, more typically:
1 get - process | gm
get-member is one of the ‘trinity’ of ‘help’-ful commands:
• get-member
• get-help
• get-command
get-help
get-help is similar to the Unix man[3].
So if you type get-help get-process, you’ll get this:
1 NAME
2 Get - Process
3
4 SYNOPSIS
5 Gets the processes that are running on the local computer or a remote computer .
6
7
8 SYNTAX
9 Get - Process [[- Name] <String []>] [- ComputerName <String []>] [- FileVersionInfo ]
[- Module ] [< CommonParameters >]
10
11 Get - Process [- ComputerName <String [] >] [- FileVersionInfo ] [- Module ] -Id
<Int32 []> [< CommonParameters >]
12
13 Get - Process [- ComputerName <String [] >] [- FileVersionInfo ] [- Module ]
-InputObject <Process []> [< CommonParameters >]
14
15
16 DESCRIPTION
17 The Get - Process cmdlet gets the processes on a local or remote computer .
18
19 Without parameters , Get - Process gets all of the processes on the local
computer . You can also specify a particular
20 process by process name or process ID (PID) or pass a process object through
the pipeline to Get - Process .
21
22 By default , Get - Process returns a process object that has detailed information
about the process and supports
8
23 methods that let you start and stop the process . You can also use the
parameters of Get - Process to get file
24 version information for the program that runs in the process and to get the
modules that the process loaded .
25
26
27 RELATED LINKS
28 Online Version : http :// go. microsoft .com/ fwlink /? LinkID =113324
29 Debug - Process
30 Get - Process
31 Start - Process
32 Stop - Process
33 Wait - Process
34
35 REMARKS
36 To see the examples , type: "get -help Get - Process -examples ".
37 For more information , type: "get -help Get - Process -detailed ".
38 For technical information , type: "get -help Get - Process -full ".
39 For online help , type: "get -help Get - Process -online "
There are a couple of wrinkles which actually make the PowerShell ‘help’ even more help-ful.
• you get basic help by typing get-help, more help by typing get-help -full and…probably the
best bit as far as I’m concerned…you can cut to the chase by typing get-help -examples
• there are lots of ‘about_’ pages. These cover concepts, new features (in for example
about_Windows_Powershell_5.0) and subjects which dont just relate to one particular command.
You can see a full list of the ‘about’ topics by typing get-help about
• get-help works like man -k or apropos. If you’re not sure of the command you want to see help
on, just type help process and you’ll see a list of all the help topics that talk about processes.
If there was only one it would just show you that topic
• Comment-based help. When you write your own commands you can (and should!) use the
comment-based help functionality. You follow a loose template for writing a comment header
block, and then this becomes part of the get-help subsystem. It’s good.
get-command
If you don’t want to go through the help system, and you’re not sure what command you need, you
can use get-command.
I use this most often with wild-cards either to explore what’s available or to check on spelling.
For example, I tend to need to look up the spelling of ConvertTo-Csv on a fairly regular basis.
PowerShell commands have a very good, very intuitive naming convention of a verb followed by a
noun (for example, get-process, invoke-webrequest), but I’m never quite sure where ‘to’ and ‘from’
go for the conversion commands.
To quickly look it up I can type:
get-command *csv*
… which returns:
9
1 $ get - command *csv*
2
3 CommandType Name ModuleName
4 ----------- ---- ----------
5 Alias epcsv -> Export -Csv
6 Alias ipcsv -> Import -Csv
7 Cmdlet ConvertFrom -Csv Microsoft . PowerShell . Utility
8 Cmdlet ConvertTo -Csv Microsoft . PowerShell . Utility
9 Cmdlet Export -Csv Microsoft . PowerShell . Utility
10 Cmdlet Import -Csv Microsoft . PowerShell . Utility
11 Application ucsvc .exe
12 Application vmicsvc .exe
Functions
Typically PowerShell coding is done in the form of functions[4]. What you do to code and write a
function is this:
Create a function in a plain text .ps1 file[5]
1 gvim say - HelloWorld .ps1
File is missing
…then source the function when they need it
1 $ . .\say - HelloWorld .ps1
…then run it
1 $ say - helloworld
2 Hello , World
Often people autoload their functions in their $profile or other startup script, as follows:
1 write - verbose " About to load functions "
2 foreach ($FUNC in $(dir $FUNCTION_DIR \*. ps1))
3 {
4 write - verbose " Loading $FUNC .... "
5 . $FUNC . FullName
6 }
## Footnotes
[1] If you wanted the equivalent of ls -ltr you would use gci | sort lastwritetime. ‘gci’ is an alias
for ‘get-childitem’, and I think, ‘sort’ is an alias for ‘sort-object’.
[2] Another way of returning all of the properties of an object is to use ‘select *’…so in this case you
could type get-process | select *
10
[3] There is actually a built-in alias man which tranlates to get-help, so you can just type man if you’re
pining for Unix.
[4] See the following for more detail on writing functions rather than scripts: http://blogs.technet.
com/b/heyscriptingguy/archive/2011/06/26/don-t-write-scripts-write-powershell-functions.aspx
[5] I’m using ‘gvim’ here, but notepad would work just as well. PowerShell has a free ‘scripting
environment’ called PowerShell ISE, but you don’t have to use it if you dont want to.
3 commands summary
alias (set aliases)
1 set - alias
More
alias (show aliases)
1 get - alias
More
apropos
1 get -help
More
basename
1 dir | select name
More
cal
No equivalent, but see the script at http://www.vistax64.com/powershell/17834-unix-cal-command.
html\char”003C\relax{}/a>
11
12
cd
1 cd
More
clear
1 clear -host
More
date
1 get -date
More
date -s
1 set -date
More
df -k
1 Get - WMIObject Win32_LogicalDisk | ft -a
More
dirname
1 dir | select directory
More
du
No equivalent, but see the link
13
echo
1 write - output
More
echo -n
1 write -host -nonewline
More
| egrep -i sql
1 | where {[ Regex ]:: Ismatch ($\_.name. tolower () , "sql ") }
More
egrep -i
1 select - string
More
egrep
1 select - string -casesensitive
More
egrep -v
1 select - string -notmatch
More
14
env
1 Get - ChildItem Env: | fl
or
get-variable
More
errpt
1 get - eventlog
More
export PS1=”$ “
1 function prompt {"$ " }
More
find
1 dir * whatever * -recurse
More
for (start, stop, step)
1 for ($i = 1; $i -le 5; $i ++) { whatever }
More
head
1 gc file.txt | select - object -first 10
More
15
history
1 get - history
More
history | egrep -i ls
1 history | select commandline | where commandline -like '*ls*' | fl
More
hostname
1 hostname
More
if-then-else
1 if ( condition ) { do -this } elseif { do -that } else {do - theother }
More
if [ -f “$FileName” ]
1 if (test -path $FileName )
More
kill
1 stop - process
More
less
1 more
More
16
locate
1 no equivalent but see link
More
ls
1 get - childitem OR gci OR dir OR ls
More
ls -a
1 ls -force
More
ls -ltr
1 dir c:\ | sort - object -property lastwritetime
More
lsusb
1 gwmi Win32_USBControllerDevice
More
mailx
1 send - mailmessage
More
man
1 get -help
More
17
more
1 more
More
mv
1 rename -item
More
pg
1 more
More
ps -ef
1 get - process
More
ps -ef | grep oracle
1 get - process oracle
More
pwd
1 get - location
More
read
1 read -host
More
18
rm
1 remove -item
More
script
1 start - transcript
More
sleep
1 start - sleep
More
sort
1 sort - object
More
sort -uniq
1 get - unique
More
tail
1 gc file.txt | select - object -last 10
More
tail -f
1 gc -tail 10 -wait file.txt
More
19
time
1 measure - command
More
touch - create an empty file
1 set - content -Path ./ file.txt -Value $null
More
touch - update the modified date
1 set - itemproperty -path ./ file.txt -name LastWriteTime -value $(get -date)
More
wc -l
1 gc ./ file.txt | measure - object | select count
More
whoami
1 [ Security . Principal . WindowsIdentity ]:: GetCurrent () | select name
More
whence or type
1 No direct equivalent , but see link
More
unalias
1 remove -item -path alias : aliasname
More
20
uname -m
1 Get - WmiObject -Class Win32_ComputerSystem | select manufacturer , model
More
uptime
1 get - wmiobject -class win32_operatingsystem | select LastBootUpTime `
More
(line continuation)
1 ` (a backtick )
More
4 commands detail - a
alias (list all the aliases)
The Powershell equivalent of typing alias at the bash prompt is:
1 get - alias
alias (set an alias)
At it’s simplest, the powershell equivalent of the unix ‘alias’ when it’s used
to set an alias is ‘set-alias’
1 set - alias ss select - string
However, there’s a slight wrinkle….
In unix, you can do this
1 alias bdump ="cd /u01/app/ oracle / admin / $ORACLE_SID /bdump /"
If you try doing this in Powershell, it doesn’t work so well. If you do this:
1 set - alias cdtemp "cd c:\ temp"
2 cdtemp
…then you get this error:
1 cdtemp : The term 'cd c:\ temp ' is not recognized as the name of a cmdlet , function ,
script file , or operable program . Check the spelling of the name , or if a path
was included , verify that the path is correct and try again.
2 At line :1 char :1
3 + cdtemp
4 + ~~~~~~
5 + CategoryInfo : ObjectNotFound : (cd c:\ temp: String ) [],
CommandNotFoundException
6 + FullyQualifiedErrorId : CommandNotFoundException
A way around this is to create a function instead:
1 remove -item -path alias : cdtemp
2 function cdtemp {cd c:\ temp}
21
22
You can then create an alias for the function:
1 set - alias cdt cdtemp
apropos
apropos is one of my favourite bash commands, not so much for what it does…but because I like the
word ‘apropos’.
I’m not sure it exists on all flavours of *nix, but in bash apropos returns a list of all the man pages
which have something to do with what you’re searching for. If apropos isn’t implemented on your
system you can use man -k instead.
Anyway on bash, if you type:
1 apropos process
…then you get:
1 AF_LOCAL [unix] (7) - Sockets for local interprocess communication
2 AF_UNIX [unix] (7) - Sockets for local interprocess communication
3 Apache2 :: Process (3 pm) - Perl API for Apache process record
4 BSD :: Resource (3 pm) - BSD process resource limit and priority functions
5 CPU_CLR [ sched_setaffinity ] (2) - set and get a process 's CPU affinity mask
6 CPU_ISSET [ sched_setaffinity ] (2) - set and get a process 's CPU affinity mask
7 CPU_SET [ sched_setaffinity ] (2) - set and get a process 's CPU affinity mask
8 CPU_ZERO [ sched_setaffinity ] (2) - set and get a process 's CPU affinity mask
9 GConf2 (rpm) - A process - transparent configuration system
The Powershell equivalent of apropos or man -k is simply get-help
1 get -help process
2
3 Name Category Module Synopsis
4 ---- -------- ------ --------
5 get - dbprocesses Function Get processes for a particul ...
6 show - dbprocesses Function Show processes for a particu ...
7 Debug - Process Cmdlet Microso ... Debugs one or more processes ...
8 Get - Process Cmdlet Microso ... Gets the processes that are ...
This is quite a nice feature of PowerShell compared to Bash. If get-help in Powershell shell scores
a ‘direct hit’ (i.e. you type something like get-help debug-process) it will show you the help for that
particular function. If you type something more vague, it will show you a list of all the help pages
you might be interested in.
By contrast if you typed man process at the Bash prompt, you’d just get
1 No manual entry for process
5 commands detail - b
basename
A rough PowerShell equivalent for the unix basename is:
1 dir <whatever > | select name
This depends on the file actually existing, whereas basename doesn’t care.
A more precise (but perhaps less concise) alternative[1] is:
[System.IO.Path]::GetFileName('c:\temp\double_winners.txt')
Notes
[1] I found [System.IO.Path]::GetFileName after reading Power Tips of the Day - Useful Path Manip-
ulations Shortcuts, which has some other useful commands
23
6 commands detail - c
cal
There’s no one-liner equivalent for the Linux cal, but there’s a useful script, with much of the cal
functionality here :
http://www.vistax64.com/powershell/17834-unix-cal-command.html\char”003C\relax{}/a>
cd
The PowerShell equivalent of cd is:
1 Set - Location
…although there is a builtin PowerShell alias cd which points at set-location
cd ~
cd ~ moves you to your home folder in both unix and Powershell.
clear
The unix clear command clears your screen. The Powershell equivalent to the unix clear is
1 clear -host
PowerShell also has built-in alias clear for clear-host.
However, it’s possibly worth noting that the behaviour of the two commands is slightly different
between the two environments.
In my Linux environment, running putty, clear gives you a blank screen by effectively scrolling
everything up, which means you can scroll it all back down.
The Powershell Clear-host on the other hand seems to wipe the previous output (actually in the
same way that cmd’s cls command does….). This could be quite a significant difference, depending
on what you want to clear and why!
24
25
cp
The Posh version of cp is
1 copy -item
The following are built-in aliases for copy-item:
1 cp
2 copy
cp -R
To recursively copy:
1 copy -recurse
7 commands detail - d
date
The Powershell equivalent of the Unix date is
1 get -date
The Powershell equivalent of the Unix date -s is
1 set -date
I was anticipating doing a fairly tedious exercise of going through all the Unix date formats and then
working out the Powershell equivalent, but discovered the Powershell Team has effectively done all
this for me. There is a Powershell option -UFormat which stands for ‘unix format’.
So the Powershell:
1 date -Uformat '%D'
2 09/08/14
is the same as the *nix
1 date +'%D'
2 09/08/14
This is handy…but I have found the odd difference. I tried this for a demo:
Unix:
1 date +' Today is %A the %d of %B, the %V week of the year %Y. My timezone is %Z, and
here it is %R'
2 Today is Monday the 08 of September , the 37 week of the year 2014. My timezone is
BST , and here it is 17:24
Powershell:
1 get -date -Uformat 'Today is %A the %d of %B, the %V week of the year %Y. My
timezone is %Z, and here it is %R'
2 Today is Monday the 08 of September , the 36 week of the year 2014. My timezone is
+01 , and here it is 17:25
26
27
I presume the discrepancy in the week of the year is to do with when the week turns - as you can see
I ran the command on a Monday. Some systems have the turn of the week being Monday, others
have it on Sunday.
I don’t know why \%Z outputs different things….and I can’t help feeling I’m being churlish pointing
this out. The -UFormat option is a really nice thing to have.
df -k
A quick and dirty Powershell equivalent to ‘df -k’ is
1 Get - WMIObject Win32_LogicalDisk -filter " DriveType =3" | ft
A slightly prettier version is this function:
1 function get - serversize { Param ( [ String ] $ComputerName )
2
3 Get - WMIObject Win32_LogicalDisk -filter " DriveType =3" -computer $ComputerName |
4 Select SystemName , DeviceID , VolumeName ,
5 @{Name =" size (GB)"; Expression ={"{0: N1}" -f($_.size /1gb)}},
6 @{Name =" freespace (GB)"; Expression ={"{0: N1}" -f($_. freespace /1gb)}}
7 }
8
9 function ss { Param ( [ String ] $ComputerName )
10 get - serversize $ComputerName | ft
11 }
….then you can just do:
1 $ ss my_server
….and get
1 SystemName DeviceID VolumeName size(GB) freespace (GB)
2 ---------- -------- ---------- -------- -------------
3 my_server C: OS 30.0 7.8
4 my_server D: App 250.0 9.3
5 my_server E: 40.0 5.0
dirname
A good PowerShell equivalent to the unix dirname is
1 gi c:\ double_winners \ chelsea .doc | select directory
However, this isn’t a direct equivalent. Here, I’m telling Powershell to look at an actual file and then
return that file’s directory. The file has to exist. The unix ‘dirname’ doesn’t care whether the file
you specify exists or not. If you type in dirname /tmp/double_winners/chelsea.doc on any Unix server
it will return /tmp/double_winners, I think. dirname is essentially a string-manipulation command.
A more precise Powershell equivalent to the unix ‘dirname’ is this
28
1 [ System .IO.Path ]:: GetDirectoryName ('c:\ double_winners \ chelsea .doc ')
….but it’s not as easy to type, and 9 times out of 10 I do want to get the folder for an existing file
rather than an imaginary one.
du
While I think there are implementations of du in PowerShell, personally my recommendation would
be to download Mark Russinovich’s ‘du’ tool, which is here:
Windows Sysinternals - Disk Usage
This is part of the Microsoft’s ‘sysinternals’ suite.
8 commands detail - e
echo
echo is an alias in PowerShell. As you would expect it’s an alias for the closest equivalent to the
Linux echo:
• write-output
You use it as follows:
write-output "Blue is the colour"
As well as write-output there are a couple of options for use in Powershell scripts and functions:
• write-debug
• write-verbose
Whether these produce any output is controlled by commandline or environment flags.
echo -n
In bash, echo -n echoes back the string without printing a newline, so if you do this:
1 $ echo -n Blue is the colour
you get:
1 Blue is the colour$
….with your cursor ending up on the same line as the output, just after the dollar prompt
Powershell has an exact equivalent of ‘echo -n’. If you type:
1 PS C:\ Users \matt > write -host -nonewline "Blue is the colour "
….then you get this:
1 PS C:\ Users \matt > write -host -nonewline "Blue is the colour "
2 Blue is the colourPS C:\ Users \matt >
Note that -nonewline doesn’t ‘work’ if you’re in the ISE.
29
30
egrep
The best PowerShell equivalent to egrep or grep is select-string:
1 select - string stamford blue_flag .txt
A nice feature of select-string which isn’t available in grep is the -context option. The -context
switch allows you to see a specified number of lines either side of the matching one. I think this is
similar to SEARCH /WINDOW option in DCL.
egrep -i
Powershell is case-insensitive by default, so:
1 select - string stamford blue_flag .txt
…would return:
blue_flag.txt:3:From Stamford Bridge to Wembley
If you want to do a case sensitive search, then you can use:
1 select - string -casesensitive stamford blue_flag .txt
egrep -v
The Powershell equivalent to the -v option would be -notmatch
1 select - string -notmatch stamford blue_flag .txt
egrep ‘this|that’
To search for more than one string within a file in bash, you use the syntax:
1 egrep 'blue|stamford ' blue_flag .txt
This will return lines which contain either ‘blue’ or ‘stamford’.
The PowerShell equivalent is to seperate the two strings with a comma, so:
1 $ select - string stamford ,blue blue_flag .txt
…returns:
1 blue_flag .txt :2:We 'll keep the blue flag flying high
2 blue_flag .txt :3: From Stamford Bridge to Wembley
3 blue_flag .txt :4:We 'll keep the blue flag flying high
31
| egrep -i sql
This is an interesting one, in that it points up a conceptual difference between PowerShell and Bash.
In bash, if you want to pipe into a grep, you would do this:
1 ps -ef | egrep sql
This would show you all the processes which include the string ‘sql’ somewhere in the line returned
by ps. The egrep is searching across the whole line. If the username is ‘mr_sql’ then a line would
be returned, and if the process is ‘sqlplus’ than a line would also be returned.
To do something similar in PowerShell you would do something more specific
1 get - process | where processname -like '*sql*'
So the string ‘sql’ has to match the contents of the property processname. As it happens, get-process
by default only returns one text field, so in this case it’s relatively academic, but hopefully it illustrates
the point.
env
The Linux ‘env’ shows all the environment variables.
In PowerShell there are two set of environment variables:
- windows-level variables and
- Powershell-level variable
Windows-level variables are given by:
1 Get - ChildItem Env: | fl
PowerShell-level variables are given by:
1 get - variable
errpt
I think errpt is possibly just an AIX thing (the linux equivalent is, I think, looking at /var/log/message).
It shows system error and log messages.
The PowerShell equivalent would be to look at the Windows eventlog, as follows
1 get - eventlog -computername bigserver -logname application -newest 15
The lognames that I typically look at are ‘system’, ‘application’ or ‘security’.
32
export PS1=“$”
In bash the following changes the prompt when you are at the command line
1 export PS1 ="$ "
The Powershell equivalent to this is:
function prompt { "$ " }
I found this on Richard Siddaway’s Blog
9 commands detail - f
find
The bash find command has loads of functionality - I could possibly devote many pages to Powershell
equivalents of the various options, but at it’s simplest the bash find does this:
1
2 find . -name '*BB.txt '
3 ./ Archive / Script_WO7171BB .txt
4 ./ Archive / Script_WO8541BB .txt
5 ./ Archive / Script_WO8645_BB .txt
6 ./ Archive / WO8559B / Script_WO8559_Master_ScriptBB .txt
7 ./ Archive / WO8559B / WO8559_finalBB .txt
8 ./ Archive / WO8559B / WO8559_part1BB .txt
9 ./ Archive / WO8559B / WO8559_part2BB .txt
The simplest Powershell equivalent of the bash find is simply to stick a -recurse on the end of a dir
command
1
2 PS x:\> dir *BB.txt -recurse
3
4 Directory : x:\ Archive \ WO8559B
5
6 Mode LastWriteTime Length Name
7 ---- ------------- ------ ----
8 ----- 28/02/2012 17:15 608 Script_WO8559_Master_ScriptBB .txt
9 ----- 28/02/2012 17:17 44 WO8559_finalBB .txt
10 ----- 28/02/2012 17:17 14567 WO8559_part1BB .txt
11 ----- 28/02/2012 17:15 1961 WO8559_part2BB .txt
12
13 Directory : x:\ Archive
14
15 Mode LastWriteTime Length Name
16 ---- ------------- ------ ----
17 ----- 15/06/2011 08:56 2972 Script_WO7171BB .txt
18 ----- 14/02/2012 16:39 3662 Script_WO8541BB .txt
19 ----- 27/02/2012 15:22 3839 Script_WO8645_BB .txt
If you want Powersehll to give you output that looks more like the Unix find then you can pipe into
| select fullname
1 PS x:\> dir *BB.txt -recurse | select fullname
33
34
2
3 FullName
4 --------
5 x:\ Archive \ WO8559B \ Script_WO8559_Master_ScriptBB .txt
6 x:\ Archive \ WO8559B \ WO8559_finalBB .txt
7 x:\ Archive \ WO8559B \ WO8559_part1BB .txt
8 x:\ Archive \ WO8559B \ WO8559_part2BB .txt
9 x:\ Archive \ Script_WO7171BB .txt
10 x:\ Archive \ Script_WO8541BB .txt
11 x:\ Archive \ Script_WO8645_BB .txt
for
for loop - start, stop, step
The equivalent of this bash:
1 for (( i = 1 ; i <= 5 ; i++ ))
2 do
3 echo "Hello , world $i"
4 done
5
6 Hello , world 1
7 Hello , world 2
8 Hello , world 3
9 Hello , world 4
10 Hello , world 5
…is
1 for ($i = 1; $i -le 5; $i ++)
2 {
3 write - output "Hello , world $i"
4 }
5
6 Hello , world 1
7 Hello , world 2
8 Hello , world 3
9 Hello , world 4
10 Hello , world 5
for loop - foreach item in a list
For the Bash
for I in Chelsea Arsenal Spuds do echo $I done
the equivalent Powershell is:
foreach ($Team in ("Chelsea", "Arsenal", "Spuds")){write-output $Team}
35
for loop - for each word in a string
For the bash:
1 london =" Chelsea Arsenal Spurs "
2 for team in $london ; do echo " $team "; done
…the equivalent Powershell is:
1 $London = " Chelsea Arsenal Spuds "
2 foreach ($Team in ( $London . split ())) {write - output $Team}
for loops - for lines in a file
Bash:
1 for team in $(egrep -v mill london .txt)
2 > do
3 > echo $team
4 > done
Posh:
1 select - string -notmatch millwall london .txt | select line | foreach {write - output
$_}
or:
1 foreach ($team in (select - string -notmatch millwall london .txt | select line))
{ $team}
for loop - for each file in a folder
Bash:
1 for LocalFile in *
2 do
3 echo $LocalFile
4 done
Posh:
1 foreach ( $LocalFile in $(gci)) {write - output $LocalFile .Name}
10 commands detail - g
Not got any commands beginning with ‘g’ yet.
36
11 commands detail - h
head
The PowerShell equivalent of the *nix head is:
1 gc file.txt | select - object -first 10
history
The Powershell equivalent of history is:
1 get - history
There is a built in alias history
It’s worth noting that history doesn’t persist across PowerShell sessions, although if you search online
there are a couple of published techniques for making it persistent.
It’s also perhaps worth noting that Powershell gives you a couple of extra bits of information, if you
want them:
1 get - history | gm -MemberType Property
2
3
4 TypeName : Microsoft . PowerShell . Commands . HistoryInfo
5
6 Name MemberType Definition
7 ---- ---------- ----------
8 CommandLine Property string CommandLine {get ;}
9 EndExecutionTime Property datetime EndExecutionTime {get ;}
10 ExecutionStatus Property System . Management . Automation . Runspaces . PipelineState
ExecutionStatus {get ;}
11 Id Property long Id {get ;}
12 StartExecutionTime Property datetime StartExecutionTime {get ;}
history | egrep -i ls
There is no direct equivalent of the shell functionality you get with set -o vi sadly. You can up-
and down- arrow by default, but if you want to search through your history then you need to do
37