Home > Back-end >  How do you add server names to an array?
How do you add server names to an array?

Time:07-21

I’m sorta new to Powershell and am learning a lot from “Powershell for SysAdmins” and came across the below I have questions about.

I see that the following is creating an array but if I wanted to add actual server names into it, do I edit “SRV1, SRV2,etc” or do I add them into “$($servers[0])” etc? If later, would it look like $(\servername[0])”?

$servers = @('SRV1','SRV2','SRV3','SRV4','SRV5')

Get-Content -Path "\$($servers[0])\c$\App_configuration.txt"

Get-Content -Path "\$($servers[1])\c$\App_configuration.txt"

Get-Content -Path "\$($servers[2])\c$\App_configuration.txt"

Get-Content -Path "\$($servers[3])\c$\App_configuration.txt"

Get-Content -Path "\$($servers[4])\c$\App_configuration.txt"

CodePudding user response:

I don't know where you found that example, but the whole point of pushing N server names into a single array is that you don't then have to repeat the same code N times - you can simply loop over the values in the array and repeat whatever operation you need to execute:

# edit this statement and replace the names with your real server names
$server = @('actualServerNameGoesHere01','actualServerNameGoesHere02','actualServerNameGoesHere03')

$server |ForEach-Object {
    # This statement will be executed for each of the names in `$servers`
    Get-Content -Path "\\$_\c$\App_configuration.txt"
}
  • Related