alias
At it’s simplest, the powershell equivalent of the unix ‘alias’ is ‘set-alias’
set-alias ss select-string
However, there’s a slight wrinkle….
In *nix, you can do this
alias bdump="cd /u01/app/oracle/admin/$ORACLE_SID/bdump/"
If you try doing this in Powershell, it doesn’t work so well:
set-alias cdtemp "cd c:\temp"
cdtemp
You get:
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.
At line:1 char:1
+ cdtemp
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (cd c:\temp:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
A way around is to create a function instead:
remove-item -path alias:cdtemp
function cdtemp {cd c:\temp}
cdtemp
you can then create an alias for the function:
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 ‘apropos’ looks like this:
apropos process
AF_LOCAL [unix] (7) - Sockets for local interprocess communication
AF_UNIX [unix] (7) - Sockets for local interprocess communication
Apache2::Process (3pm) - Perl API for Apache process record
BSD::Resource (3pm) - BSD process resource limit and priority functions
CPU_CLR [sched_setaffinity] (2) - set and get a process's CPU affinity mask
CPU_ISSET [sched_setaffinity] (2) - set and get a process's CPU affinity mask
CPU_SET [sched_setaffinity] (2) - set and get a process's CPU affinity mask
CPU_ZERO [sched_setaffinity] (2) - set and get a process's CPU affinity mask
GConf2 (rpm) - A process-transparent configuration system
The Powershell equivalent of ‘apropos’ or ‘man -k’ is simply ‘get-help’
get-help process
Name Category Module Synopsis
---- -------- ------ --------
get-dbprocesses Function Get processes for a particular databases [SH]
show-dbprocesses Function Show processes for a particular database [SH]
show-timeandprocesses Function ...
function-show-timeandprocesses... Extern... function-show-timeandprocesses.ps1 ...
Debug-Process Cmdlet Evil empire.PowerShell.M... Debugs one or more processes running on the local computer.
Get-Process Cmdlet Evil empire.PowerShell.M... Gets the processes that are running on the local computer or a rem...
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 type ‘man process’ at the Bash prompt, you’d just get
No manual entry for process
basename
dir | select name
or, following on from a PowerShell.com ‘Power Tips of the Day’
[System.IO.Path]::GetFileName('c:\temp\tax_dodgers.txt')
cal
There’s no one-liner equivalent for the Linux ‘cal’, but I’ve downloaded the code at:
http://www.vistax64.com/powershell/17834-unix-cal-command.html
… and turned it into a function
cd
Set-Location
clear
The unix ‘clear’ command clears your screen. The Powershell equivalent to the unix ‘clear’ is
clear-screen
PowerShell also has built-in alias ‘clear’ for ‘clear-screen’.
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 back down. ‘Clear-screen’ 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!
cp
The Posh version of cp
is
copy-item
The following are built-in aliases for copy-item
:
cp
copy
cp -R
To recursively copy:
copy -recurse
date
The Powershell equivalent of the Unix ‘date’ is
get-date
The Powershell equivalent of the Unix ‘date -s’ is
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:
date -Uformat '%D'
09/08/14
is the same as the *nix
date +'%D'
09/08/14
This is handy but I have found the odd difference. I tried this for a demo:
Unix:
date +'Today is %A the %d of %B, the %V week of the year %Y. My timezone is %Z, and here it is %R'
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:
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'
Today is Monday the 08 of September, the 36 week of the year 2014. My timezone is +01, and here it is 17:25
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….but 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
Get-WMIObject Win32_LogicalDisk -filter "DriveType=3" | ft
A slightly prettier version is this function:
function get-serversize { Param( [String] $ComputerName)
Get-WMIObject Win32_LogicalDisk -filter "DriveType=3" -computer $ComputerName |
Select SystemName, DeviceID, VolumeName,
@{Name="size (GB)";Expression={"{0:N1}" -f($_.size/1gb)}},
@{Name="freespace (GB)";Expression={"{0:N1}" -f($_.freespace/1gb)}}
}
function ss { Param( [String] $ComputerName)
get-serversize $ComputerName | ft
}
….then you can just do:
PS C:\Windows\system32> ss my_server
SystemName DeviceID VolumeName size(GB) freespace(GB)
---------- -------- ---------- -------- -------------
my_server C: OS 30.0 7.8
my_server D: App 250.0 9.3
my_server E: 40.0 5.0
dirname
gi c:\temp\x.txt | select directory
Note: this isn’t a direct equivalent. The unix ‘dirname’ doesn’t care whether the file you specify exists or not. If you type in ‘dirname /tmp/tax_fiddle/google.doc’ on any server it will return ‘/tmp/tax_fiddle’, I think. ‘dirname’ is essentially a string-manipulation thing.
The Powershell equivalent above actually needs the file to really exist. You could get a direct equivalent using the split method on the string I think, but it would be a bit more long-winded….and not necessarily very much more useful.
Another note: for some reason or another, possibly not unrelated to the quantity of London Pride I swallowed last night, I was under the impression that the unix ‘dirname’ only returned the name of the folder immediately above the specified file, not the whole path. It doesn’t.
Anyway if you did want that from Powershell:
get-item $(get-item c:\temp\x.txt).directory | select name
….would return just
temp
Another note: a more direct Powershell equivalent to the unix ‘dirname’ is this
[System.IO.Path]::GetDirectoryName('c:\tax_fiddlers\google.doc')
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 Evil empire’s ‘sysinternals’ suite.
echo
write-host
echo -n
‘echo -n’ echoes back the string without printing a newline, so if you do this:
$ echo -n Google paid �3.4m in 2011.
you get:
Google paid �3.4m in 2011.$
….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’:
PS C:\Windows\system32> write-host -nonewline Google paid �3.4m in 2011.
Google paid �3.4m in 2011.PS C:\Windows\system32>
| egrep -i sql
i.e. pipe into an egrep.
| where {[Regex]::Ismatch($_.name.tolower(), "sql") }
egrep -i
Powershell is case-insensitive by default
select-string elvis top1000.txt
If you want to do a case sensitive search, then you can use:
select-string -casesensitive Henry c:\henry8.txt
egrep -v
select-string -notmatch Henry c:\henry8.txt
env
The Linux ‘env’ shows all the environment variables.
In PowerShell there are two set of environment variables:
Windows-level variables, given by:
Get-ChildItem Env: | fl
PowerShell-level variables, given by:
get-variable
errpt
I think errpt is just an AIX thing((the bash equivalent is, I think, looking at /var/log/message)). It shows system error and log messages
get-eventlog -computername bigserver -logname application -newest 15
export PS1=”$ “
function prompt {
"$ "
}
I don’t entirely understand this – but presumably Powershell looks for a function called prompt and runs it every time you hit return.
I found this on Fun with prompts – Richard Siddaway’s Blog
find
The bash ‘find’ command could or should perhaps have a page of Powershell equivalents to itself…maybe I’ll do that at some stage.
Anyway at it’s simplest the bash ‘find’ does this:
find . -name '*BB.txt'
./Archive/Script_WO7171BB.txt
./Archive/Script_WO8541BB.txt
./Archive/Script_WO8645_BB.txt
./Archive/WO8559B/Script_WO8559_Master_ScriptBB.txt
./Archive/WO8559B/WO8559_finalBB.txt
./Archive/WO8559B/WO8559_part1BB.txt
./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
PS x:\> dir *BB.txt -recurse
Directory: x:\Archive\WO8559B
Mode LastWriteTime Length Name
---- ------------- ------ ----
----- 28/02/2012 17:15 608 Script_WO8559_Master_ScriptBB.txt
----- 28/02/2012 17:17 44 WO8559_finalBB.txt
----- 28/02/2012 17:17 14567 WO8559_part1BB.txt
----- 28/02/2012 17:15 1961 WO8559_part2BB.txt
Directory: x:\Archive
Mode LastWriteTime Length Name
---- ------------- ------ ----
----- 15/06/2011 08:56 2972 Script_WO7171BB.txt
----- 14/02/2012 16:39 3662 Script_WO8541BB.txt
----- 27/02/2012 15:22 3839 Script_WO8645_BB.txt
This may be what you want. If you want Powersehll to give you output that looks more like the Unix find then you can pipe into ‘| select fullname’
PS x:\> dir *BB.txt -recurse | select fullname
FullName
--------
x:\Archive\WO8559B\Script_WO8559_Master_ScriptBB.txt
x:\Archive\WO8559B\WO8559_finalBB.txt
x:\Archive\WO8559B\WO8559_part1BB.txt
x:\Archive\WO8559B\WO8559_part2BB.txt
x:\Archive\Script_WO7171BB.txt
x:\Archive\Script_WO8541BB.txt
x:\Archive\Script_WO8645_BB.txt
for
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}
for loop – for each word in a string
For the bash:
london="Chelsea Arsenal Spurs"
for team in $london; do echo "$team"; done
…the equivalent Powershell is:
$London = "Chelsea Arsenal Spuds"
foreach ($Team in ($London.split())) {write-output $Team}
for loop – start, stop, step
The equivalent of this bash:
for
do
echo "Hello, world $i"
done
Hello, world 1
Hello, world 2
Hello, world 3
Hello, world 4
Hello, world 5
…is
for ($i = 1; $i -le 5; $i++)
{
write-output "Hello, world $i"
}
Hello, world 1
Hello, world 2
Hello, world 3
Hello, world 4
Hello, world 5
for loops – for lines in a file
Bash:
for team in $(egrep -v mill london.txt)
> do
> echo $team
> done
Posh:
select-string -notmatch millwall london.txt | select line | foreach {write-output $_}
or:
foreach ($team in (select-string -notmatch millwall london.txt | select line)) {$team}
for loop – for each file in a folder
Bash:
for LocalFile in *
do
echo $LocalFile
done
Posh:
foreach ($LocalFile in $(gci)) {write-output $LocalFile.Name}
head
gc henry8.txt | select-object -first 10
history
history
This is an alias for get-history
It’s worth noting that history doesn’t persist across PowerShell sessions.
PowerShell magazine has a way of coding around this by auto-magically saving the history on exit, and re-loading on startup, although presumably this wouldn’t work if, say, your PC crashed. Anyway the article is here:
PowerShell Magazine » #PSTip Automatically persist history
history | egrep -i elvis
history | select commandline | where-object {$_.commandline -like '*elvis*'} | fl
hostname
This isn’t Powershell, it’s a standard-ish Windows executable that on my machine lives in c:\windows\system32
hostname
Details are here: Evil empire Windows XP – Hostname
if-then-else
Actually this is if-then-elif-else
HOUR_OF_DAY=$(date +'%H')
if [ $HOUR_OF_DAY -lt 6 ]
then
echo "Still nightime"
elif [ $HOUR_OF_DAY -lt 12 ]
then
echo "Morning has broken"
elif [ $HOUR_OF_DAY -lt 18 ]
then
echo "After noon"
else
echo "Nightime again"
fi
…and this is the Powershell equivalent of the bash shell if-then-elif-else
[int]$HourOfDay = $(get-date -UFormat '%H')
if ( $HourOfDay -lt 6 )
{
write-output "Still nightime"
}
elseif ( $HourOfDay -lt 12 )
{
write-output "Morning has broken"
}
elseif ( $HourOfDay -lt 18 )
{
write-output "After noon"
}
else
{
write-output "Nightime again"
}
if [ -f “$FileName” ]
Bash:
export FileName=~/.matt
if [ -f "$FileName" ]
then
echo "$FileName found."
else
echo "$FileName not found."
fi
Posh:
$FileName = "c:\powershell\.matt.ps1x"
if (test-path $FileName)
{echo "$FileName found"}
else
{echo "$FileName not found"}
kill
stop-process
A typical usage in Powershell might be:
get-process | select starttime , id, ProcessName | where {$_.processname -like 'iex*'}
stop-process 5240
Just noticed there is actually a builtin alias ‘kill’ which will work just as well:
get-alias k*
CommandType Name
----------- ----
Alias kill -> Stop-Process
locate
At the time of writing, I haven’t tried it out but Chrissy LeMaire (website) has written
Script Invoke-Locate: PowerShell port of GNU findutils’ locate and updatedb
….which sounds ideal
ls
Get-ChildItem or gci or dir
there’s also a get-item, but I’m not sure what that gives you beyond get-childitem
ls -ltr
…or in DOS dir /OD
dir c:\tax_dodgers | sort-object -property lastwritetime
lsusb
gwmi Win32_USBControllerDevice
mailx
$PSEmailServer = "exchange_server.domain.co.uk"
send-mailmessage -to eric.schmidt@gmail.com -from tax.man@hrmc.gov.uk -subject "Pay fair taxes"
man
get-help
mv
Rename-Item
ps -ef
get-process
get-process -ComputerName bigserver Var* .
ps -ef | grep oracle
get-process oracle
get-process oracle | select ProcessName, StartTime
get-process oracle | select ProcessName -expand Threads |
select Id,StartTime,TotalProcessorTime, WaitReason
….can also do the following:
get-process |
where {$_.PeakWorkingSet -gt 1Mb } | select ProcessName,PeakWorkingSet
pwd
Get-Location
read
In *nix
read -p "How much tax did Google pay in 2011? " small_number
echo $small_number
In Powershell
$small_number = read-host "How much tax did Google pay in 2011? "
How much tax did Google pay in 2011? : £3.4m
$small_number
£3.4m
To not echo the input to screen, it’s
-assecurestring
and I think stty -echo/stty echo in bash
rm
Remove-Item
script
start-transcript
sleep
start-sleep -seconds 5
or
start-sleep -milliseconds 250
or just:
sleep 3
…will sleep for 3 seconds
sort
gc c:\henry8.txt | sort-object
sort -uniq
get-unique
gc c:\temp\2000.txt | sort | gu -asstring
Note: this only works as far I can see if you sort it first
Note 2: get-unique IS case sensitive
Note 3: I haven’t quite worked out the circumstances, but this seems to work better for me if I specify ‘-asstring’
sqlplus
You need to have the sql module loaded for this to work, or be running the sqlplus thing from within SSMS
Invoke-Sqlcmd -ServerInstance -query "Select blah" -database _catalog
strings
I don’t know of a direct PowerShell equivalent to the unix ‘strings’ command, but there is a version of strings in Evil empire’s Sysinternals suite: Strings
tail
gc henry8.txt | select-object -last 10
tail -f
gc -tail 10 -wait c:\windows\windowsupdate.log
time
The Powershell equivalent of the bash shell ‘time’ is ‘measure-command’.
So, in bash you would do this:
time egrep ORA- *log
….and get all the egrep output, then
real 0m4.649s
user 0m0.030s
sys 0m0.112s
In Powershell, you would do this
measure-command {select-string ORA- *.sql}
…and get…
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 105
Ticks : 1057357
TotalDays : 1.22379282407407E-06
TotalHours : 2.93710277777778E-05
TotalMinutes : 0.00176226166666667
TotalSeconds : 0.1057357
TotalMilliseconds : 105.7357
…you don’t get the ‘user CPU’ time and ‘system CPU’ time, but you do get the added bonus of seeing how long the command took rendered as a fraction of a day!
tnsping
Tnsping is actually an Oracle tool which checks whether the Oracle listener is up without logging onto the database. Using a .udl file isn’t really a direct equivalent, but it’s a handy place to record this
set-content -Path d:\temp\test_connection.udl -Value ($null)
…then for this file
ii -Path d:\temp\test_connection.udl
The set-content bit was gotten from Super User, the contributor being user techie007
touch – create an empty file
set-content -Path c:\temp\new_empty_file.dat -Value $null
I found the set-content command at set-content bit was gotten from Super User, the contributor being user techie007
touch – update the modified date
set-itemproperty -path c:\temp\new_empty_file.dat -name LastWriteTime -value $(get-date)
I got this from a comment by Manung Han on the Lab49 Blog. Doug Finke sharestouch function in a later comment on the same post that fully implements the linux command.
wc -l
gc c:\temp\file.txt | measure-object | select count
to show the number of non-blank lines:
gc c:\temp\file.txt | measure-object -line
Was reminded of this by article on measure-object at: Evil empire Certified Professional Magazine Online
whoami
[Security.Principal.WindowsIdentity]::GetCurrent() | select name
whence or type
Couple of things here at least.
This shows the sort of thing (exe, bat, alias, function):
get-command whoami
CommandType Name ModuleName
----------- ---- ----------
Application whoami.exe
….and if it what you’re looking for is a file in the path, this will find it
foreach ($FOLDER in $ENV:PATH.split(";") ) { dir $FOLDER\whoami.exe -ea Si | select fullname }
FullName
--------
C:\Windows\system32\whoami.exe
This splits the path into its constituent folders, then does a ‘dir’ to see if the file (in this case I’m looking for whoami.exe) and returns the full path and file if it’s there.
unalias
remove-item -path alias:cdtemp
uname -s
uname -s
in Unix, according to the man page, gives the ‘kernel-version’ of the OS. This is the ‘top-level version’ of the Unix that you’re on. Typical values are ‘Linux’, or ‘AIX’ or ‘HP-UX’. So, on my laptop, typing uname -s
gives:
Linux
I’ve only used this when writing a Unix script which have to do slightly different things on different flavours of unix.
Obviously, there’s only one manufacturer for Windows – Evil empire[^1]. So there’s no direct equivalent to uname -s
. The closest equivalent on Powershell would I think be:
get-wmiobject -class win32_operatingsystem | select caption
This returns:
caption
-------
Evil empire Windows 7 Professional
or
Evil empire Windows 8.1 Pro
or
Evil empire(R) Windows(R) Server 2003, Standard Edition
or
Evil empire Windows Server 2008 R2 Enterprise
or
Evil empire Windows Server 2012 Standard
uname -n
According to the Linux help, uname -n
does this:
-n, --nodename
print the network node hostname
So, typing uname -n
gives
$ uname -n
nancy.one2one.co.uk
I haven’t found a neat equivalent for this in Powershell, but this works:
get-wmiobject -class win32_computersystem | select dnshostname, domain
The output is:
dnshostname domain
----------- ------
nancy one2one.co.uk
uname -r
uname -r
gives the kernel release in Unix. The output varies depending on the flavour of Unix – Wikipedia has a good list of examples
On my system uname -r
gives:
2.6.32-200.20.1.el5uek:
The best Powershell equivalent would seem to be:
get-wmiobject -class win32_operatingsystem | select version
…which gives:
6.1.7601
The 7601 is Evil empire’s build number.
uname -v
uname -v
typically gives the date of the unix build. As far a I can think, there isn’t a Powershell equivalent
uname -m
To be honest, I’m not entirely sure what uname -m shows us on Unix. The wikipedia page for uname shows various outputs none of whic hare hugely useful.
Running uname -m
on my server gives:
x86_64
Is this a PowerShell equivalent?
$ get-ciminstance -class cim_computersystem | select SystemType
SystemType
----------
x64-based PC
uname -m
Get-WmiObject -Class Win32_ComputerSystem | select manufacturer, model
uptime
On most, but from memory possibly not all, flavours of *nix ‘uptime’ tells you how long the server has been up and running
$ uptime
15:54:24 up 9 days, 5:43, 2 users, load average: 0.10, 0.09, 0.07
A rough equivalent to show how long the swerver (or PC) has been running Powershell is:
get-wmiobject -class win32_operatingsystem | select LastBootUpTime
….of course you can also do
get-wmiobject -class win32_operatingsystem -ComputerName my_server | select LastBootUpTime
…to get the bootup time for a remote server, or PC.
I turned this into a couple of functions and an alias to get the info I most often need and format it nicely
function get-os {
[CmdletBinding()]
Param ( [String] $ComputerName = ".")
get-wmiobject -class win32_operatingsystem -computer $ComputerName |
select __Server,
caption,
Manufacturer,
InstallDate,
LastBootUpTime,
Version,
ServicePackMajorVersion,
ServicePackMinorVersion
}
function show-os {
[CmdletBinding()]
Param ( [String] $ComputerName = ".")
get-os $ComputerName |
ft @{Label="Server"; Width = 12 ; Expression={$_.__Server}},
@{Name="Versh" ; Width=30; Expression = {$_.caption.replace('Evil empire Windows ','') } },
@{Label="SPMajor"; Width = 7; Expression={$_.ServicePackMajorVersion}},
@{Label="SPMinor"; Width = 7; Expression={$_.ServicePackMinorVersion}},
@{l="Version"; e={$_.Version }; Width = 12},
@{l="Install"; e={$_.InstallDate.substring(0,8) }; width=9},
@{Label="Booted"; Expression={$_.LastBootUpTime.substring(0,12)}; width=14}
}
set-alias sos show-os
So having loaded this I just run:
PS C:\Windows\system32> sos myserver
Server Versh SPMajor SPMinor Version Install Booted
—— —– ——- ——- ——- ——- ——
myserver Evil empire(R) Windows(R) Ser… 2 0 5.2.3790 20111213 2014040217
\ (line continuation)
The Powershell line continuation character is the horrible ‘backtick’ i.e. this:
`
On my leopard, the backtick is to the left of the ‘1’ key.
Todo
shutdown -r - restart-computer
more/less
find
crontab -l
ls -R
.profile
bg
cut
env
eval
file
find
free (memory)
fuser filename
head
tee
/var/log/message
write
& (run in background)
PS1 (line contunuation prompt)
declare -F
type
Parameter passing
cut -f 3
for (p127)
while (p139)
until
case
select p113, p136
String comparisons p118
File attribute operations p122
fileinfo
Number comparisons p126
IFS (internal field separator) p127
PS3
getopts p145
let p145
arrays p160
here -documents p165
debugging stuff p221
-n (syntax check)
-v
-x
#todo10 #todo
keyword: poshbash poshunix
Follow Me!