Reputation: 45
Currently I have the below script that works however I have over 30 servers and they often change so i was curious if there was a simpler way to get the $ServerList
variable updated with the import data from each of my servers. The server path is the same and I could maintain a Server.txt
file with all the server names. Any ideas on how to simplify this to work with a larger list of servers that I can update when needed without having to add lines to the powershell script?
$Headers = "Extension","Server IP","Comment"
$1 = Import-Csv "\\Server1\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server1'}}
$2 = Import-Csv "\\Server2\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server2'}}
$3 = Import-Csv "\\Server3\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server3'}}
$4 = Import-Csv "\\Server4\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server4'}}
$ServerList = $1,$2,$3,$4
Upvotes: 1
Views: 1393
Reputation: 7499
A method I would use for something like this would be to make a Function for it. Here's some untested sample code.
Function Import-ServerListCSV($serverName){
$Headers = "Extension","Server IP","Comment"
Import-Csv "\\$serverName\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={$serverName}}
}
$ServerList = "Server1","Server2","Server3","Server4" | % {Import-ServerListCSV $_}
Upvotes: 0
Reputation: 58941
Yes, you can use the Get-Content cmdlet to get a list of servers (you have to create the Server.txt
first). Then you can use the Foreach-Object cmdlet (alias %
) to iterate over it and use the current server:
$Headers = "Extension","Server IP","Comment"
$servers = Get-Content 'Your_path_to_server.txt'
$ServerList = $servers |
% { $server = $_; Import-Csv ("\\{0}\app\test\Stations.txt" -f $server) -Header $Headers |
Select-Object *, @{n='Server Name';e={$server}} }
Now you don't need to change anything on the script if you add a server. Here is the same script but maybe a little better to understand for you:
$Headers = "Extension","Server IP","Comment"
$serverNames = Get-Content 'Your_path_to_server.txt'
$ServerList = @()
foreach ($serverName in $serverNames)
{
$ServerList += Import-Csv "\\$serverName\app\test\Stations.txt" -Header "Extension","Server IP","Comment" |
Select-Object *, @{n='Server Name';e={$serverName}}
}
Upvotes: 1