PowerShell is an interactive shell and scripting language from Microsoft that rethinks what a command shell is all about. It has very interesting capabilities above and beyond the familiar Unix shells, and there is a strong ecosystem and community.
In this two-part tutorial, you'll learn about some of the cool stuff you can do with PowerShell, its history, its architecture, its concepts, and how it compares with a Unix shell like Bash. Get ready for an exciting journey!
Installing PowerShell
If you're on Windows 10, you're good to go. Otherwise, download it from the Microsoft website.
Once PowerShell is installed, the first thing you want to do is to enable script execution. Launch PowerShell as administrator and type: Set-ExecutionPolicy RemoteSigned
. You need to do it just once. Now, update the help files: Update-Help -Force
.
Cool Stuff You Can Do With PowerShell
Let's start with a quick demonstration of the breadth and depth of PowerShell. This is just a somewhat arbitrary list to whet your appetite. It is not comprehensive, nor are these necessarily the most impressive things you can do with PowerShell.
Play Videos
Here is a cool one-liner to play video files (or any media file):
(New-object –COM WMPlayer.OCX).openPlayer("Path to your video")
It will open a media player window and start playing your video immediately.
Here Strings
PowerShell has one of the most readable and visually pleasing solutions to multi-line strings, AKA "here strings". You just start with @"
and end with "@
. Note that the start and end markers must be on their own line, separate from the content in between. Here is an example:
$x = "@ 123 456 789 @"
Generate random numbers
Pick a random number between 1 and 100:
1..50 | Get-Random
This is a simple pipeline. The left side can generate all the integers from 1 to 50 (inclusive), and then it's fed to the Get-Random cmdlet that picks one of them.
Work With the Clipboard
PowerShell supports the clipboard in depth. You can get and set objects of different formats. Obviously, plain text is possible, but you can also work with images, HTML, RTF, and even files.
Here, I select some files in explorer and then I get them from the clipboard in PowerShell:
23:43:05 C:\Users\the_g> Get-Clipboard -Files Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 9/15/2016 11:41 PM 135890 Capture.PNG -a---- 9/16/2016 10:09 PM 3179548 20160917_110605.jpg -a---- 9/16/2016 10:09 PM 4623977 20160917_110734.jpg
Speak
PowerShell can speak too!
Add-Type -AssemblyName System.speech $synth = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer $synth.Speak("PowerShell to the people")
Get All Running Virtual Machines
Here is a little pipeline to list all the running virtual machines:
Get-VM | Where-Object { $_.State -eq "Running" }
Display Progress Bar
PowerShell can display a nice progress bar during long operations. Here is an example that calculates recursively the total size of all the files under the current directory:
$files = Get-ChildItem . -Recurse $total = 0 For ($i = 1; $i -le $files.Count-1; $i++) { Write-Progress -Activity "Calculating total size..." -status $files[$i].Name -PercentComplete ($i / $files.Count * 100) $total += $files[$i].Length Start-Sleep -Milliseconds 50 } Write-Host "Total size: $($total / 1MB)"
PowerShell History
PowerShell 1.0 was released in 2006, but its inventor Jeffery Snover started working on it much earlier. Check out the 2002 manifesto. PowerShell has come a long way. Windows was way behind in terms of command-line facilities. System administrators and power users had to make do with the meager offerings of cmd.exe and batch files. There were a few feeble attempts to improve the situations with Windows scripting hosts that allowed scripting system objects using VBScript or JScript, but there a lot of issues with that approach.
PowerShell changed all that and very quickly. It didn't just match the command-line capabilities of *nix environments but leapfrogged ahead with many innovations and unprecedented consistency and ease of use.
Today, PowerShell is at version 5.1. Along the years and versions, PowerShell's capabilities and hosting environments grew significantly.
PowerShell 1.0 supported local administration of Windows machines (including Windows Server 2003).
PowerShell 2.0 was integrated with Windows 7 and Windows Server 2008 R2. It added support for remoting and significantly increased the capabilities of PowerShell with background jobs, transactions, events, debugging, a GUI development environment, and many new cmdlets.
PowerShell 3.0 was released as part of the Windows management framework. It was installed on Windows 8 and Windows Server 2012. It added scheduled jobs, session connectivity, automatic module loading, and many new commands.
PowerShell 4.0 was integrated with Windows 8.1 and Windows Server 2012 R2. It added support for desired state configuration, enhanced debugging, network diagnostics, and the -PipelineVariable
switch.
PowerShell 5.0 was released as part of Windows management framework 5. PowerShell 5.1 was released as part of the Windows 10 anniversary updates. New features include PowerShell class definitions, .NET enumerations, remote debugging and debugging background jobs, DSC local configuration manager, and many more DSC improvements.
PowerShell: The Scripting Language
PowerShell is a very powerful programming language. It can run scripts, obviously, but it has also more advanced mechanisms like modules, custom cmdlets, and classes. PowerShell is a multi-paradigm language that supports the object-oriented, functional, and procedural paradigms.
But maybe the most important aspect of PowerShell is that it is a full-fledged .NET language. It creates and uses .NET assemblies objects programmed in any language, and objects passing through PowerShell's pipeline are .NET objects. PowerShell is also strongly typed, but when it's convenient you can ignore it, and you don't have to specify the types if you don't want to.
Procedural Scripting
To program procedurally, you need functions, conditionals, and loops. PowerShell has all that. The comparison operators may surprise you as they don't use the typical symbols. Instead you have: -eq
(equal), -lt
(less than), -gt
(greater than), -ge
(greater or equal), etc.
Here is a conditional logic example that gets input from the user and verifies it is valid. Note the use of the -as
operator to try to convert the input to an integer. If it fails, the result is $null
.
$value = 44 $in = Read-Host "Guess a number between 1 - 100" $guess = $in -as [int] if ((($guess -eq $null) -or ($guess -lt 1)) -or ($guess -gt 100)) { Write-Host "$guess is NOT an integer between 1 - 100" Exit } if ($guess -eq $value) { Write-Host "You Win!" } elseif ($guess -lt $value) { Write-Host "Too low" } else { Write-Host "Too high" }
PowerShell has many facilities and cmdlets to work with collections and slice and dice them, so loops are not often needed. But, just in case you're so inclined, there are plenty of loopy constructs in PowerShell. You can use For loops, ForEach loops, While loops, Do-While loops, and even special ForEach-Object loops. Here are some examples.
For ( $i = 0; $i -lt 100; $i += 20 ) { $i } 0 20 40 60 80 $list = 1..5 ForEach ($item in $list) { $item * 3} 3 6 9 12 15 $later = $(Get-Date).AddSeconds(5) while ($(Get-Date) -lt $later) { "Are we there yet?" sleep 1 } PS C:\WINDOWS\system32> $later = $(Get-Date).AddSeconds(5) while ($(Get-Date) -lt $later) { "Are we there yet?" sleep 1 } Are we there yet? Are we there yet? Are we there yet? Are we there yet? Are we there yet?
Functional Programming
PowerShell is all about functional programming. The pipeline is a functional execution environment where you compose functions/cmdlets dynamically. You can do it interactively or you can do in a script. If you want to do explicit functional programming, you can do it too, but the syntax is a little cumbersome. Check out this article: Functional Programming in PowerShell.
Object-Oriented Programming
You've already seen how to use .NET objects and the objects passing through the pipeline. Let's define a class in PowerShell and do some basic OO. I create here a class for a game character with health and armor that can take damage and calculate its health. There is also an IsAlive()
method that checks if health > 0. I use a constructor.
Note that you must instantiate PowerShell classes using [<class name>]::new()
. The New-Object syntax is not supported as of PowerShell 5.1.
class Character { [string] $Name [int] $Health [int] $AttackDamage [float] $Armor Character([string] $name, [int] $health, [int] $attackDamage, [float] $armor) { $this.Name = $name $this.Health = $health $this.AttackDamage = $attackDamage $this.Armor = $armor } [bool] IsAlive() { return $this.Health -gt 0 } [void] TakeDamage([int] $damage) { if ($this.armor -gt 0) { $damage = $damage - 0.4 * $this.Armor * $damage } $this.Health -= $damage } } $c = [Character]::new("xxx", 50, 10, 1.0) $c.TakeDamage(20) $c.IsAlive() True $c.Health 38 $c.TakeDamage(40) $c.Health 14 $c.TakeDamage(40) $c.Health -10 $c.IsAlive() False
You can even do inheritance if you like, but I feel that at this point you should probably use a different language.
Interactive Script Environment
PowerShell comes with its own IDE for script development that includes an interactive window, multi-tabbed for scripts with code completion, built-in help on all the cmdlets, and much more. It is a very slick tool, and I recommend that you give it a try.
Conclusion
You've now seen the capabilities of PowerShell as a scripting language and learned a little about its design objectives and its history. In part two, I'll cover in depth the interactive aspects of PowerShell.
No comments:
Post a Comment