V Britt
V Britt

Reputation: 25

Add a list of variables in a powershell script

I am sure this is obvious but for the life of me I can not find the information. Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them. There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self. Something like (and I know this doesn't work as writen:

$servers= @(
    Server1
    Server2
    Server3
    )

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid. If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes. Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

Upvotes: 0

Views: 3953

Answers (3)

zdan
zdan

Reputation: 29450

If you want to be able to paste the server names directly into your script without using an intermediate 2nd file, just paste the list into a multi-line string like this:

$serversTxt = @"
server1
server2
server3
"@

$servers = $serversTxt -split "`n"

Upvotes: 1

AdminOfThings
AdminOfThings

Reputation: 25001

From the comments, it appears you want to copy and paste a list of systems into a script and have it process as an array. One way to do this is using here-strings.

$servers = @'
server1
server2
server3
'@ -split '\r?\n'

Output

$servers
server1
server2
server3
$servers.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array

Just paste your server list between the @''@ lines. Keep in mind that @' and '@ should be on lines with no other values.

See About Quoting Rules for information on here-strings.

Upvotes: 4

tommymaynard
tommymaynard

Reputation: 2152

Filter out the empty lines:

Get-Content -Path .\servers.txt | Where-Object -FilterScript {$_ -ne ''}

Edit: Sure, you can include your server names within your script if you choose to do that. If you have an array, as you've created in your example, then simply iterate over them within a looping construct, doing something to each server, on each loop.

$Servers = @('Server1','Server2','Server3')

Foreach ($Server in $Servers) {
    "Do something to $Server."
} # End Foreach.

Do something to Server1.
Do something to Server2.
Do something to Server3.

Upvotes: 1

Related Questions