Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you add server names to an array?

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading