Share via


PowerShell Examples: Range Operator

Find an available IP address within a subnet:

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

Open an RDP session with machines QA1 through QA7:

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

Read lines from a text file and write out only lines that begin with uppercase character:

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

The example below 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.

    $VM = Get-VM

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

Original content for this article from: http://blog.richprescott.com/2012/01/powershell-range-operator-real-world.html

See Also