使用 Select-Object 从导入的服务器列表设置变量

Set a Variable from an Imported List of Servers with Select-Object

目前我有下面的脚本可以工作但是我有超过 30 个服务器并且它们经常变化所以我很好奇是否有更简单的方法来使用每个服务器的导入数据更新 $ServerList 变量我的服务器。服务器路径相同,我可以维护一个包含所有服务器名称的 Server.txt 文件。关于如何简化它以使用我可以在需要时更新而无需向 powershell 脚本添加行的更大服务器列表的任何想法?

$Headers = "Extension","Server IP","Comment"
 = Import-Csv "\Server1\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server1'}}
 = Import-Csv "\Server2\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server2'}}
 = Import-Csv "\Server3\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server3'}}
 = Import-Csv "\Server4\app\test\Stations.txt" -Header $Headers | Select-Object *, @{n='Server Name';e={'Server4'}}

$ServerList = ,,,

是的,您可以使用 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(别名 %)对其进行迭代并使用当前服务器:

$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}} } 

现在,如果您添加服务器,则无需更改脚本中的任何内容。 这是相同的脚本,但对您来说可能更好理解一些:

$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}}
}

我会使用的一种方法是为它创建一个函数。这是一些未经测试的示例代码。

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 $_}