Powershellorg A Unix Persons Guide To Powershell Master
Powershellorg A Unix Persons Guide To Powershell Master
people
PowerShell.org
Introduction to PowerShell for Unix peo-
ple
PowerShell.org
https://www.penflip.com/powershellorg/a-unix-persons-guide-to-powershell
©2015 PowerShell.org
Contents
3
1 About
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:
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.
A full introduction to PowerShell is beyond the scope of this e-book. My recommendations for an
end-to-end view of PowerShell are:
• 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
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
In Bash you are working with characters, or tab-delimited fields. In PowerShell you work with field
names, which are known as ‘properties’.
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
• get-member
• get-help
• get-command
get-help
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
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
1 set - alias
More
1 get - alias
More
apropos
1 get -help
More
basename
More
cal
11
12
cd
1 cd
More
clear
1 clear -host
More
date
1 get -date
More
date -s
1 set -date
More
df -k
More
dirname
More
du
echo
1 write - output
More
echo -n
More
| egrep -i sql
More
egrep -i
1 select - string
More
egrep
More
egrep -v
More
14
env
or
get-variable
More
errpt
1 get - eventlog
More
export PS1=”$ “
More
find
More
More
head
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
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
More
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
More
uptime
More
(line continuation)
1 ` (a backtick )
More
4 commands detail - a
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
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
21
22
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
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
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
cd ~
clear
The unix clear command clears your screen. The Powershell equivalent to the unix clear is
1 clear -host
24
25
cp
cp -R
To recursively copy:
1 copy -recurse
7 commands detail - d
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
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
….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
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
….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
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
As well as write-output there are a couple of options for use in Powershell scripts and functions:
• write-debug
• write-verbose
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 "
29
30
egrep
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
…would return:
blue_flag.txt:3:From Stamford Bridge to Wembley
egrep -v
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
…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
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
export PS1=“$”
In bash the following changes the prompt when you are at the command line
1 export PS1 ="$ "
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
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
…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
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}
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
36
11 commands detail - h
head
history
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