Powershell Tip: Increment Number Value at end of Variable/String using Foreach Loop

Many times there is a need to run through a list of servers or hostnames that have number increments and you don’t want to have to import a text file or csv.

I have a linux bash background and in bash you can do something like below to do a task against a list of servers:
for hostname in server{1..3}
do
echo $hostname
done
Output:
server1
server2
server3

In powershell you can use this format for it to work:
1..3 | % {“Server$_”}
The % is shorthand for foreach.
Server1
Server2
Server3

Now you can increment through a list of servers that are in numerical order!

Advertisements

One Response to Powershell Tip: Increment Number Value at end of Variable/String using Foreach Loop

  1. sharkrit says:

    Hi, What if I have a running alphabet in the middle of array?
    For example:
    $Servers =
    Server-A01
    Server-A02
    Server-A03



    Server-Z99

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: