2017-10-11 2 views
3

Mon csv existant ressemble à ceci:Ecrire Informations en csv existant

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

Maintenant, je veux vérifier si l'hôte est en ligne ou non et d'écrire une nouvelle colonne nommée « Etat » avec le résultat dans mon csv . Cela fonctionne très bien dans la console, mais comment diable puis-je exporter le résultat dans mon csv?

Répondre

2

Vous pouvez utiliser l'applet de commande Add-Member pour ajouter un membre (statut) à votre entité actuelle:

$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

Vous pouvez créer un PSCustomObject au sein de votre boucle 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 
0

Vous devez utiliser Cmdlet Out-File qui vous permet d'envoyer une sortie en pipeline directement dans un fichier texte.

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

}