powershellorg a unix persons guide to powershell master

37
Introduction to PowerShell for Unix people PowerShell.org

Upload: epilefsantiago

Post on 18-Aug-2015

225 views

Category:

Documents


5 download

DESCRIPTION

Powershell para gente de UNIX

TRANSCRIPT

Introduction to PowerShell for UnixpeoplePowerShell.orgIntroduction to PowerShell for Unix peo-plePowerShell.orgThis project can be followed at:https://www.penip.com/powershellorg/a-unix-persons-guide-to-powershell2015 PowerShell.orgContents31 AboutPrincipal author: Matt PennyThis e-book is intended as a Quick Start guide to PowerShell for people who already know Bash orone of the other Unix shells.The book has 3 elements:an introductory chapter which covers some PowerShell conceptsa summary list of PowerShell equivalents of Unix commands in one e-book chaptera detailed discussion of Powershell equivalents of Unix commands, organised in the alphabeticalorder of the unix commandVisit www.penip.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. Theauthors encourage you to redistribute this le as widely as possible, but ask that you do not modifythe document.PowerShell.orgeBooks are works-in-progress, andmanyare curatedbymembers of the com-munity. Weencourageyoutocheckbackfor neweditions at least twiceayear, byvisitingwww.penip.com/powershellorg.You can download this book in a number of dierent formats (including EPUB, PDF, MicrosoftWord and Plain Text) by clicking Download on the right side of the page.PDF Users: Penips PDF export often doesnt include the entire ebook content. Weve reportedthis problem to them; in the meantime, please consider using a dierent format, such as EPUB,when youre downloading the book.You may register to make corrections, contributions, and other changes to the text - we welcomeyour contributions! However, we recommend you check out our contributor tips and notes beforejumping in.You may also subscribe to our monthly e-mail TechLetter for notications of updated e-book editions.Visit PowerShell.org for more information on the newsletter.42 Introduction to PowerShell for UnixpeopleThe point of this section is to outline a few areas which I think *nix people should pay particularattention to when learning Powershell.Resources for learning PowerShellA fullintroduction to PowerShell is beyond the scope of this e-book. My recommendations for anend-to-end view of PowerShell are:Learn Windows PowerShell in a Month of Lunches - Written by powershell.orgs Don Jonesand Jeery Hicks, I would guess that this is the book that most people have used to learnPowershell. Its the Llama book of Powershell.Microsoft Virtual Academys Getting Started with PowerShell and Advanced Tools & Script-ing with PowerShell Jump Start courses - these are recordings of day long webcasts, and areboth free.unix-like aliasesPowerShell 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:\temp2 Mode LastWriteTime Length Name3 ---- ------------- ------ ----4 -a--- 22/02/2015 16:51 25773 all_the_details.md5 -a--- 20/02/2015 07:31 3390 commands -summary.md56These can be quite useful when youre switching between shells, although I found that it can beirritating when the muscle-memory kicks in and you nd yourself typing ls-ltr in PowerShell andget an error. The ls is just an alias for the PowerShell get-childitem and the Powershell commanddoesnt understand -ltr[1].the pipelineThe PowerShell pipeline is much the same as the Bash shell pipeline. The output of one commandis piped to another one with the | symbol.The big dierence 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 its going to be a big deal, but its 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-70whereas In PowerShell you would do this:1 get-process | select ProcessNameIn Bash you working with characters, or tab-delimited elds. In PowerShell you work with eld names,which are known as properties.get-help, get-command, get-memberget-memberWhen you run a PowerShell command, such as get-history only a subset of the get-history outputis returned to the screen.In the case of get-history, by default two properties are shown - Id and Commandline1 $ get-history23 Id CommandLine4 -- -----------5 1 dir -recurse c:\tempbut get-history has 4 other properties which you might or might not be interested in:1 $ get-history | select *23 Id : 14 CommandLine : dir -recurse c:\temp5 ExecutionStatus : Completed6 StartExecutionTime : 06/05/2015 13:46:567 EndExecutionTime : 06/05/2015 13:47:077The disparity between what is shown and what is available is even greater for more complex entitieslike process. By default get-process shows 8 columns, but there are actually over 50 properties (aswell as 20 or so methods) available.Thefull rangeof whatyoucanreturnfromaPowerShell commandisgivenbythe get-membercommand[2].To run get-member, you pipe the output of the command youre interested in to it, for example:1 get-process | get-member.or, more typically:1 get-process | gmget-member is one of the trinity of help-ful commands:get-memberget-helpget-commandget-helpget-help is similar to the Unix man[3].So if you type get-helpget-process, youll get this:1 NAME2 Get-Process34 SYNOPSIS5 Gets the processes that are running on the local computer or a remote computer.678 SYNTAX9 Get-Process [[-Name] ] [-ComputerName ] [-FileVersionInfo][-Module] []1011 Get-Process [-ComputerName ] [-FileVersionInfo] [-Module] -Id []1213 Get-Process [-ComputerName ] [-FileVersionInfo] [-Module]-InputObject []141516 DESCRIPTION17 The Get-Process cmdlet gets the processes on a local or remote computer.1819 Without parameters , Get-Process gets all of the processes on the localcomputer. You can also specify a particular20 process by process name or process ID (PID) or pass a process object throughthe pipeline to Get-Process.2122 By default, Get-Process returns a process object that has detailed informationabout the process and supports823 methods that let you start and stop the process. You can also use theparameters of Get-Process to get file24 version information for the program that runs in the process and to get themodules that the process loaded.252627 RELATED LINKS28 Online Version: http://go.microsoft.com/fwlink/?LinkID=11332429 Debug-Process30 Get-Process31 Start-Process32 Stop-Process33 Wait-Process3435 REMARKS36 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 typingget-help, more help by typingget-help-full andprobably thebest bit as far as Im concernedyou can cut to the chase by typing get-help-examplesthere are lots of about_ pages. These cover concepts, newfeatures (in for exampleabout_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-helpaboutget-help works like man-k or apropos. If youre not sure of the command you want to see helpon, just type helpprocess and youll see a list of all the help topics that talk about processes.If there was only one it would just show you that topicComment-based help. When you write your own commands you can (and should!) use thecomment-based help functionality. You follow a loose template for writing a comment headerblock, and then this becomes part of the get-help subsystem. Its good.get-commandIf you dont want to go through the help system, and youre not sure what command you need, youcan use get-command.I use this most often with wild-cards either to explore whats available or to check on spelling.For example, I tendtoneedtolookupthespellingof ConvertTo-Csvonafairlyregular basis.PowerShell commands have a very good, very intuitive naming convention of a verb followed by anoun (for example,get-process,invoke-webrequest), but Im never quite sure where to and fromgo for the conversion commands.To quickly look it up I can type:get-command*csv* which returns:91 $ get-command *csv*23 CommandType Name ModuleName4 ----------- ---- ----------5 Alias epcsv -> Export-Csv6 Alias ipcsv -> Import-Csv7 Cmdlet ConvertFrom -Csv Microsoft.PowerShell.Utility8 Cmdlet ConvertTo -Csv Microsoft.PowerShell.Utility9 Cmdlet Export-Csv Microsoft.PowerShell.Utility10 Cmdlet Import-Csv Microsoft.PowerShell.Utility11 Application ucsvc.exe12 Application vmicsvc.exeFunctionsTypically PowerShell coding is done in the form of functions[4]. What you do to code and write afunction is this:Create a function in a plain text .ps1 le[5]1 gvim say-HelloWorld.ps1File is missingthen source the function when they need it1 $ . .\say-HelloWorld.ps1then run it1 $ say-helloworld2 Hello, WorldOften 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.FullName6 }## Footnotes[1] If you wanted the equivalent of ls-ltr you would use gci|sortlastwritetime. gci is an aliasfor 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 youcould 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 yourepining 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] Im using gvim here, but notepad would work just as well. PowerShellhas a free scriptingenvironment called PowerShell ISE, but you dont have to use it if you dont want to.3 commands summaryalias (set aliases)1 set-aliasMorealias (show aliases)1 get-aliasMoreapropos1 get-helpMorebasename1 dir | select nameMorecalNo equivalent, but see the script at http://www.vistax64.com/powershell/17834-unix-cal-command.html\char003C\relax{}/a>1112cd1 cdMoreclear1 clear-hostMoredate1 get-dateMoredate -s1 set-dateMoredf -k1 Get-WMIObject Win32_LogicalDisk | ft -aMoredirname1 dir | select directoryMoreduNo equivalent, but see the link13echo1 write-outputMoreecho -n1 write-host -nonewlineMore| egrep -i sql1 | where {[Regex]::Ismatch($\_.name.tolower(), "sql") }Moreegrep -i1 select-stringMoreegrep1 select-string -casesensitiveMoreegrep -v1 select-string -notmatchMore14env1 Get-ChildItem Env: | florget-variableMoreerrpt1 get-eventlogMoreexport PS1=$ 1 function prompt {"$ " }Morend1 dir *whatever* -recurseMorefor (start, stop, step)1 for ($i = 1; $i -le 5; $i++) {whatever}Morehead1 gc file.txt | select-object -first 10More15history1 get-historyMorehistory | egrep -i ls1 history | select commandline | where commandline -like '*ls*' | flMorehostname1 hostnameMoreif-then-else1 if ( condition ) { do-this } elseif { do-that } else {do-theother}Moreif [ -f $FileName ]1 if (test-path $FileName)Morekill1 stop-processMoreless1 moreMore16locate1 no equivalent but see linkMorels1 get-childitem OR gci OR dir OR lsMorels -a1 ls -forceMorels -ltr1 dir c:\ | sort-object -property lastwritetimeMorelsusb1 gwmi Win32_USBControllerDeviceMoremailx1 send-mailmessageMoreman1 get-helpMore17more1 moreMoremv1 rename-itemMorepg1 moreMoreps -ef1 get-processMoreps -ef | grep oracle1 get-process oracleMorepwd1 get-locationMoreread1 read-hostMore18rm1 remove-itemMorescript1 start-transcriptMoresleep1 start-sleepMoresort1 sort-objectMoresort -uniq1 get-uniqueMoretail1 gc file.txt | select-object -last 10Moretail -f1 gc -tail 10 -wait file.txtMore19time1 measure-commandMoretouch - create an empty le1 set-content -Path ./file.txt -Value $nullMoretouch - update the modied date1 set-itemproperty -path ./file.txt -name LastWriteTime -value $(get-date)Morewc -l1 gc ./file.txt | measure-object | select countMorewhoami1 [Security.Principal.WindowsIdentity]::GetCurrent() | select nameMorewhence or type1 No direct equivalent , but see linkMoreunalias1 remove-item -path alias:aliasnameMore20uname -m1 Get-WmiObject -Class Win32_ComputerSystem | select manufacturer , modelMoreuptime1 get-wmiobject -class win32_operatingsystem | select LastBootUpTime `More(line continuation)1 ` (a backtick)More4 commands detail - aalias (list all the aliases)The Powershell equivalent of typing alias at the bash prompt is:1 get-aliasalias (set an alias)At its simplest, the powershell equivalent of the unix alias when its usedto set an alias is set-alias1 set-alias ss select-stringHowever, theres a slight wrinkle.In unix, you can do this1 alias bdump="cd /u01/app/oracle/admin/$ORACLE_SID/bdump/"If you try doing this in Powershell, it doesnt work so well. If you do this:1 set-alias cdtemp "cd c:\temp"2 cdtempthen 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 pathwas included , verify that the path is correct and try again.2 At line:1 char:13 + cdtemp4 + ~~~~~~5 + CategoryInfo : ObjectNotFound: (cd c:\temp:String) [],CommandNotFoundException6 + FullyQualifiedErrorId : CommandNotFoundExceptionA way around this is to create a function instead:1 remove-item -path alias:cdtemp2 function cdtemp {cd c:\temp}2122You can then create an alias for the function:1 set-alias cdt cdtempaproposapropos is one of my favourite bash commands, not so much for what it doesbut because I like theword apropos.Im not sure it exists on all avours of *nix, but in bashapropos returns a list of all the man pageswhich have something to do with what youre searching for. If apropos isnt implemented on yoursystem you can use man-k instead.Anyway on bash, if you type:1 apropos processthen you get:1 AF_LOCAL [unix] (7) - Sockets for local interprocess communication2 AF_UNIX [unix] (7) - Sockets for local interprocess communication3 Apache2::Process (3pm) - Perl API for Apache process record4 BSD::Resource (3pm) - BSD process resource limit and priority functions5 CPU_CLR [sched_setaffinity] (2) - set and get a process's CPU affinity mask6 CPU_ISSET [sched_setaffinity] (2) - set and get a process's CPU affinity mask7 CPU_SET [sched_setaffinity] (2) - set and get a process's CPU affinity mask8 CPU_ZERO [sched_setaffinity] (2) - set and get a process's CPU affinity mask9 GConf2 (rpm) - A process-transparent configuration systemThe Powershell equivalent of apropos or man-k is simply get-help1 get-help process23 Name Category Module Synopsis4 ---- -------- ------ --------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. Ifget-help in Powershell shell scoresa direct hit (i.e. you type something like get-helpdebug-process) it will show you the help for thatparticular function. If you type something more vague, it will show you a list of all the help pagesyou might be interested in.By contrast if you typed manprocess at the Bash prompt, youd just get1 No manual entry for process5 commands detail - bbasenameA rough PowerShell equivalent for the unix basename is:1 dir | select nameThis depends on the le actually existing, whereas basename doesnt 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 commands236 commands detail - ccalTheres no one-liner equivalent for the Linuxcal, but theres a useful script, with much of thecalfunctionality here :http://www.vistax64.com/powershell/17834-unix-cal-command.html\char003C\relax{}/a>cdThe PowerShell equivalent of cd is:1 Set-Locationalthough there is a builtin PowerShell alias cd which points at set-locationcd ~cd~ moves you to your home folder in both unix and Powershell.clearThe unix clear command clears your screen. The Powershell equivalent to the unix clear is1 clear-hostPowerShell also has built-in alias clear for clear-host.However, its possibly worth noting that the behaviour of the two commands is slightly dierentbetween the two environments.InmyLinuxenvironment, runningputty, cleargivesyouablankscreenbyeectivelyscrollingeverything 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 thesame way that cmds cls command does.). This could be quite a signicant dierence, dependingon what you want to clear and why!2425cpThe Posh version of cp is1 copy-itemThe following are built-in aliases for copy-item:1 cp2 copycp -RTo recursively copy:1 copy -recurse7 commands detail - ddateThe Powershell equivalent of the Unix date is1 get-dateThe Powershell equivalent of the Unix date-s is1 set-dateI was anticipating doing a fairly tedious exercise of going through all the Unix date formats and thenworking out the Powershell equivalent, but discovered the Powershell Team has eectively done allthis for me. There is a Powershell option -UFormat which stands for unix format.So the Powershell:1 date -Uformat '%D'2 09/08/14is the same as the *nix1 date +'%D'2 09/08/14This is handybut I have found the odd dierence. 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, andhere it is %R'2 Today is Monday the 08 of September , the 37 week of the year 2014. My timezone isBST, and here it is 17:24Powershell:1 get-date -Uformat 'Today is %A the %d of %B, the %V week of the year %Y. Mytimezone 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:252627I presume the discrepancy in the week of the year is to do with when the week turns - as you can seeI ran the command on a Monday. Some systems have the turn of the week being Monday, othershave it on Sunday.I dont know why\%Z outputs dierent things.and I cant help feeling Im being churlish pointingthis out. The -UFormat option is a really nice thing to have.df -kA quick and dirty Powershell equivalent to df -k is1 Get-WMIObject Win32_LogicalDisk -filter "DriveType=3" | ftA slightly prettier version is this function:1 function get-serversize { Param( [String] $ComputerName)23 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 }89 function ss { Param( [String] $ComputerName)10 get-serversize $ComputerName | ft11 }.then you can just do:1 $ ss my_server.and get1 SystemName DeviceID VolumeName size(GB) freespace(GB)2 ---------- -------- ---------- -------- -------------3 my_server C: OS 30.0 7.84 my_server D: App 250.0 9.35 my_server E: 40.0 5.0dirnameA good PowerShell equivalent to the unix dirname is1 gi c:\double_winners\chelsea.doc | select directoryHowever, this isnt a direct equivalent. Here, Im telling Powershell to look at an actual le and thenreturn that les directory. The le has to exist. The unix dirname doesnt care whether the leyou specify exists or not. If you type in dirname/tmp/double_winners/chelsea.doc on any Unix serverit will return /tmp/double_winners, I think. dirname is essentially a string-manipulation command.A more precise Powershell equivalent to the unix dirname is this281 [System.IO.Path]::GetDirectoryName('c:\double_winners\chelsea.doc').but its not as easy to type, and 9 times out of 10 I do want to get the folder for an existing lerather than an imaginary one.duWhile I think there are implementations ofdu in PowerShell, personally my recommendation wouldbe to download Mark Russinovichs du tool, which is here:Windows Sysinternals - Disk UsageThis is part of the Microsofts sysinternals suite.8 commands detail - eechoecho is an alias in PowerShell. As you would expect its an alias for the closest equivalent to theLinux echo: write-outputYou use it as follows:write-output"Blueisthecolour"As well as write-output there are a couple of options for use in Powershell scripts and functions: write-debug write-verboseWhether these produce any output is controlled by commandline or environment ags.echo -nIn bash, echo-n echoes back the string without printing a newline, so if you do this:1 $ echo -n Blue is the colouryou get:1 Blue is the colour$.with your cursor ending up on the same line as the output, just after the dollar promptPowershell 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 doesnt work if youre in the ISE.2930egrepThe best PowerShell equivalent to egrep or grep is select-string:1 select-string stamford blue_flag.txtA nice feature of select-string which isnt available ingrep is the-context option. The -contextswitch allows you to see a specied number of lines either side of the matching one. I think this issimilar to SEARCH/WINDOW option in DCL.egrep -iPowershell is case-insensitive by default, so:1 select-string stamford blue_flag.txtwould return:blue_flag.txt:3:FromStamfordBridgetoWembleyIf you want to do a case sensitive search, then you can use:1 select-string -casesensitive stamford blue_flag.txtegrep -vThe Powershell equivalent to the -v option would be -notmatch1 select-string -notmatch stamford blue_flag.txtegrep this|thatTo search for more than one string within a le in bash, you use the syntax:1 egrep 'blue|stamford ' blue_flag.txtThis 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.txtreturns:1 blue_flag.txt:2:We'll keep the blue flag flying high2 blue_flag.txt:3:From Stamford Bridge to Wembley3 blue_flag.txt:4:We'll keep the blue flag flying high31| egrep -i sqlThis is an interesting one, in that it points up a conceptual dierence between PowerShell and Bash.In bash, if you want to pipe into a grep, you would do this:1 ps -ef | egrep sqlThis would show you all the processes which include the string sql somewhere in the line returnedbyps. The egrep is searching across the whole line. If the username is mr_sql then a line wouldbe 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 specic1 get-process | where processname -like '*sql*'So the string sql has to match the contents of the property processname. As it happens, get-processby default only returns one text eld, so in this case its relatively academic, but hopefully it illustratesthe point.envThe Linux env shows all the environment variables.In PowerShell there are two set of environment variables:- windows-level variables and- Powershell-level variableWindows-level variables are given by:1 Get-ChildItem Env: | flPowerShell-level variables are given by:1 get-variableerrptI 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 follows1 get-eventlog -computername bigserver -logname application -newest 15The lognames that I typically look at are system, application or security.32export PS1=$In bash the following changes the prompt when you are at the command line1 export PS1="$ "The Powershell equivalent to this is:functionprompt{"$"}I found this on Richard Siddaways Blog9 commands detail - fndThe bash find command has loads of functionality - I could possibly devote many pages to Powershellequivalents of the various options, but at its simplest the bash find does this:12 find . -name '*BB.txt'3 ./Archive/Script_WO7171BB.txt4 ./Archive/Script_WO8541BB.txt5 ./Archive/Script_WO8645_BB.txt6 ./Archive/WO8559B/Script_WO8559_Master_ScriptBB.txt7 ./Archive/WO8559B/WO8559_finalBB.txt8 ./Archive/WO8559B/WO8559_part1BB.txt9 ./Archive/WO8559B/WO8559_part2BB.txtThe simplest Powershell equivalent of the bash find is simply to stick a -recurse on the end of a dircommand12 PS x:\> dir *BB.txt -recurse34 Directory: x:\Archive\WO8559B56 Mode LastWriteTime Length Name7 ---- ------------- ------ ----8 ----- 28/02/2012 17:15 608 Script_WO8559_Master_ScriptBB.txt9 ----- 28/02/2012 17:17 44 WO8559_finalBB.txt10 ----- 28/02/2012 17:17 14567 WO8559_part1BB.txt11 ----- 28/02/2012 17:15 1961 WO8559_part2BB.txt1213 Directory: x:\Archive1415 Mode LastWriteTime Length Name16 ---- ------------- ------ ----17 ----- 15/06/2011 08:56 2972 Script_WO7171BB.txt18 ----- 14/02/2012 16:39 3662 Script_WO8541BB.txt19 ----- 27/02/2012 15:22 3839 Script_WO8645_BB.txtIf you want Powersehll to give you output that looks more like the Unix nd then you can pipe into|selectfullname1 PS x:\> dir *BB.txt -recurse | select fullname333423 FullName4 --------5 x:\Archive\WO8559B\Script_WO8559_Master_ScriptBB.txt6 x:\Archive\WO8559B\WO8559_finalBB.txt7 x:\Archive\WO8559B\WO8559_part1BB.txt8 x:\Archive\WO8559B\WO8559_part2BB.txt9 x:\Archive\Script_WO7171BB.txt10 x:\Archive\Script_WO8541BB.txt11 x:\Archive\Script_WO8645_BB.txtforfor loop - start, stop, stepThe equivalent of this bash:1 for (( i = 1 ; i do3 > echo $team4 > donePosh: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 le in a folderBash:1 for LocalFile in *2 do3 echo $LocalFile4 donePosh:1 foreach ($LocalFile in $(gci)) {write-output $LocalFile.Name}10commands detail - gNot got any commands beginning with g yet.3611commands detail - hheadThe PowerShell equivalent of the *nix head is:1 gc file.txt | select-object -first 10historyThe Powershell equivalent of history is:1 get-historyThere is a built in alias historyIts worth noting that history doesnt persist across PowerShell sessions, although if you search onlinethere are a couple of published techniques for making it persistent.Its also perhaps worth noting that Powershell gives you a couple of extra bits of information, if youwant them:1 get-history | gm -MemberType Property234 TypeName: Microsoft.PowerShell.Commands.HistoryInfo56 Name MemberType Definition7 ---- ---------- ----------8 CommandLine Property string CommandLine {get;}9 EndExecutionTime Property datetime EndExecutionTime {get;}10 ExecutionStatus Property System.Management.Automation.Runspaces.PipelineStateExecutionStatus {get;}11 Id Property long Id {get;}12 StartExecutionTime Property datetime StartExecutionTime {get;}history | egrep -i lsThere is no direct equivalent of the shell functionality you get withset-ovi sadly. You can up-and down- arrow by default, but if you want to search through your history then you need to do37