PowerShell range operator: real-world examples

The beauty of PowerShell is how it includes little tidbits that seem so simple but can make your job much easier.  One example of this is the range operator '..'  I have run into multiple occasions where it came in handy and kept me from having to use an external program or perform manual steps.

For example, if I wanted to find an available IP address within a subnet, I could load a network scanning tool or use this one-liner in PowerShell:

    1..255 | %{Test-Connection 192.168.1.$_ -Count 1}

The above line will ping all IP addresses in the 192.168.1 subnet.  On a similar note, if I had seven test machines that I wanted to open an RDP session with I could use the following one-liner:

    1..7 | %{mstsc /v:QA$_}

The command above would open an RDP session with machines QA1 through QA7.  This next example isn't so much a real-world example but was a question that a PowerSheller was confronted with in an interview.


With a little knowledge of ASCII characters, I could create an array of uppercase characters and compare it against the first letter of each line as it was piped in via Get-Content.

    Get-Content file.txt | ?{(65..90 | %{[Char]$_}) -contains $_[0]}

While this approach is not the most economical when it comes to scaling, it suits the purpose for a quick interview question.  

My last example is one that allows you to test out your command on a subset of items before releasing the hounds on the whole array, so to say.

    $VM = Get-VM
    $VM[0] | Move-VM -Datastore DS02
    $VM[1..$VM.Count] | Move-VM -Datastore DS02

The example above uses the PowerCLI snapin from VMware.  The first line retrieves all of your VMs and stores them in the $VM variable.  Before you move all of the VMs to the new datastore in bulk, you can grab the first VM in the array and move it as a test.  If the test is successful, you can then run the same command with a slight modification to move the rest.  Using the 1..$VM.Count range operator allows you to count the total number of VMs in your array and move all of them to the new datastore, while skipping over the one that you already moved.

And there you have it, a few examples of what you can do to save yourself some time with just a simple feature as a range operator.

1 comment:

  1. Thanks Rich. I really like the last example showing order of operations in PowerShell.
    [1..$VM.Count].
    All examples are great real world examples. Thanks for sharing!

    ReplyDelete