First steps with Windows Powershell
After a training session with a group of colleagues, I wanted to put this together for future reference and for getting started the next time I actually want to automate something on a windows host. As such, this is not a full tutorial but rather a loose collection of facts and Q&A.
For a good listing of the various versions and platforms, have a look at the wikipedia article.
Facts
$PSVersionTable
holds the Version of the currently running PowerShell instance- PowerShell lets you chain so called cmdlets which originate from the core modules or from modules included in software packages like Microsoft Exchange Server
- cmdlets mostly adhere to a syntax describing a CRUD pattern:
New-..., Get-..., Set-..., Remove-...
- PowerShell comes with the ISE (integrated scripting environment) which is an IDE to compose, manage and run scripts
- the file name extension for scripts is
.ps1
GetHelp <cmdlet>
shows the help entry for that cmdlet (it might be necessary to runUpdate-Help
to generate the help content on that host)- piping output from one command to the input of another is done with the
|
symbol. Be aware that unlike on UNIX-like systems, this passes along actual objects and not simply lines of text. - filtering the output of a command by text can still be done by with
findstr
(the PowerShell equivalent forgrep
) - pipe output to
More
so that output can be controlled by keyboard cursors or the space key Get-Member
retrieves a list of all member (attributes and methods) of a given object- running scripts might be disabled via execution policy. You may activate it permanently on that host with
Set-Execution-Policy unrestricted
- capitalization doesn’t matter:
Get-Member
is equivalent toget-member
Get-Command
lists installed cmdlets
Investigate
- how are encodings dealt with? Ineresting: http://superuser.com/questions/327492/default-powershell-to-emitting-utf-8-instead-of-utf-16
- remote execution
- does every cmdlet always output lists of objects even if there is only one object to be returned (kind of like bash commands always return a list of lines, potentially just one)?
- how is white space treated? how about newlines?
- how to organize scripts? how to load, eval or require scripts?
- do scripts halt when an error is encountered (bash scripts only do that with the -e switch)?
- variable scope?
- is there a canonical way for dependency management (like bundler for ruby or compozer for php)?
- what data types are there, or is there just <list-of-objects>
Examples
List available logs
Get-EventLog -list
How to grep the logs for (e.g.) “Update”:
Get-EventLog System | findstr Update