将信息写入现有的csv

时间:2017-10-11 12:12:12

标签: powershell csv export-to-csv

我现有的csv看起来像这样:

"Name","Surename","Workstation"
"Doe","John","PC1"
"Fonzarelli","Arthur","PC4"
"Tribbiani","Joey","PC77"

现在,我想检查主机是否在线,并将名为“Status”的新列写入我的csv。

$file = Import-Csv "C:\Scripts\WS-Status.csv"

Foreach ($ws in $file) {

    If (Test-Connection $ws.Workstation -Count 1 -Quiet) {

        Write-Host $ws.Workstation "is online"
    }

    Else {Write-Host $ws.Workstation "is offline"}

}

它在控制台中工作正常,但我怎样才能将结果导出到我的csv中?

3 个答案:

答案 0 :(得分:2)

您可以在PSCustomObject循环中创建ForEach

$file = Import-Csv "C:\Scripts\WS-Status.csv"

Foreach ($ws in $file) {

    if(Test-Connection $ws.Workstation -Count 1 -Quiet){
        Write-Host $ws.Workstation "is online"
        $status = "Online"
    }else{
        Write-Host $ws.Workstation "is offline"
        $status = "Offline"
    }

    [array]$result += [PSCustomObject] @{
        Name        = $ws.Name
        Surename    = $ws.Surename
        Workstation = $ws.Workstation
        Status      = $status
    }

}

$result | Export-Csv thing.csv -NoTypeInformation

答案 1 :(得分:2)

您可以使用Add-Member cmdlet将成员(状态)添加到当前实体:

$file = Import-Csv "C:\Scripts\WS-Status.csv"
Foreach ($ws in $file) 
{
    if (Test-Connection $ws.Workstation -Count 1 -Quiet) 
    {
        Add-Member -InputObject $ws -NotePropertyName "Status" -NotePropertyValue "online"
    }
    else 
    {
        Add-Member -InputObject $ws -NotePropertyName "Status" -NotePropertyValue "offline"
    }
}

$file | Export-Csv "C:\Scripts\WS-Status.csv" -NoTypeInformation

答案 2 :(得分:0)

您必须使用Out-File cmdlet,它允许您将流水线输出直接发送到文本文件。

$file = Import-Csv "C:\Scripts\WS-Status.csv"

Foreach ($ws in $file) {

    If (Test-Connection $ws.Workstation -Count 1 -Quiet) {
      $ws.Workstation + " is online" | Out-File -Append OutPutFile.csv
    }
    Else {
       $ws.Workstation + ' is offline' | Out-File -Append OutPutFile.csv
    }

}