PowerShell is King – Generate an array of server names, with the same length and the same prefix

Basic Idea and Challenge

PowerShell is all about automation, and creating a loop in PowerShell that creates an array of numbers is easy, add a prefix to that and hey you have an array

1..10 | ForEach-Object {"LC-SRV-" + $_}    

The output.

The Magical -F

But, there is a small issue, the names of the server names that i need to be generated is kind of correct, but wrong, or “almost” great, I need the length to be the same. That can be fixed by using the magical –f.

1..10 | ForEach-Object {"LC-SRV-{0:D3}" -f $_}    

The Output.

The Function

So, now it looks the way I need it to be, and if you need to use it often, let’s create a function for it.

Function Create-VIAComputerName{    
$Servers = $($LowNumber..$HigNumber| ForEach-Object {"$ComputerPrefix{0:D3}" -f $_})   
Return $Servers    
Create-VIAComputerName -ComputerPrefix LC-SRV- -LowNumber 1 -HigNumber 64   


The Output.


Categories: PowerShell

Tagged as:

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.