从CSV读取会在变量

时间:2016-01-26 11:06:48

标签: csv powershell

我有这段代码:

$servers = Import-Csv "sources.csv"
$computername = $servers.server
$ServiceName = $servers.services

sources.csv包含以下内容..

Server,Services
BRWS40,winrm
BRWS84,winrm

我有一个foreach,而Write-Host就在其中,它会输出:

Write-Host "$computername - $ServiceName" -ForegroundColor black -BackgroundColor red

我得到的输出是:

BRWS40 BRWS84 - winrm winrm

而我想要每行一台计算机和服务。

BRWS40 - winrm

我做错了什么?

我修改了here的代码。

2 个答案:

答案 0 :(得分:2)

$servers = Import-Csv "sources.csv"sources.csv的内容作为自定义对象列表导入变量$servers

$computername = $servers.server将每个对象的server属性的值选择为变量$computername,从而生成计算机名称列表。

$ServiceName = $servers.services选择每个对象的services属性值到变量$ServiceName中,从而生成服务名称列表。

请注意,$array.property仅适用于PowerShell v3及更高版本,因为早期版本不会自动展开数组以获取元素属性,但尝试访问数组对象本身的属性。如果数组没有这样的属性,结果将是$null,否则它将是数组属性的值。无论哪种方式,它都不会成为你想要的。要在所有PowerShell版本中进行属性扩展,请使用Select-Object -Expand或在ForEach-Object语句中回显该属性:

$computername = $servers | Select-Object -Expand server
$computername = $servers | ForEach-Object { $_.server }

当您将数组变量放入字符串("$computername - $ServiceName")时,数组元素将由$OFS字符(默认为空格)连接,因此"$computername"变为BRWS40 BRWS84并且"$ServiceName"变为winrm winrm

要获取每个计算机的相应服务名称,您需要在循环中处理$servers,例如:

foreach ($server in $servers) {
  Write-Host ('{0} - {1}' -f $server.Server, $server.Services) ...
}

如果您不需要特定的输出格式,也可以使用其中一个Format-* cmdlet,例如Format-Table

Import-Csv "sources.csv" | Format-Table -AutoSize

答案 1 :(得分:1)

你实际上必须遍历你的结果:

$servers = Import-Csv "sources.csv"

$servers | %{
    $computername = $_.server
    $ServiceName = $_.services

    write-host "$computername - $ServiceName" -foregroundcolor black -backgroundcolor red
}

或使用Format-Table cmdlet:

$servers | Format-Table
相关问题