如果带有字符串的Else语句,则导出为CSV

时间:2017-04-13 15:38:52

标签: powershell

我是一名PowerShell新手,正在创建一个小脚本,用于从文本文件导入笔记本电脑和工作站列表,ping它们以查看它们是否在我们的网络上并继续检查计算机的代理状态/配置。

如果计算机不在线,我希望有一个文件说$工作站不在线。

我遇到的问题是将失败字符串与其他数据一起转换为CSV,我可以单独导出IF和Else,但如果可能的话,将它放在一个CSV上会很好。

有什么想法?谢谢!

$workstation=Get-content C:\Scripts\workstation.txt

$forloop=ForEach ($workstation in $workstation) {

       if (Test-Connection -ComputerName $workstation -Count 1 -Quiet) {Get-Service -ComputerName $workstation | where-object {$_.Name -eq 'xxx Agent'} | select displayname, name, starttype, status |
        export-csv -Path C:\Scripts\therealdeal.c }

       Else {Write-Output "$workstation not available Out"}
       }

$forloop | Out-File C:\scripts\output.csv 

1 个答案:

答案 0 :(得分:0)

好的,如果是我,我会先测试哪些工作站在线,然后报告哪些工作站处于脱机状态,然后处理剩下的工作。

#Load workstations
$workstations=Get-content C:\Scripts\workstation.txt
#Find which ones are online
[array]$OnlineWorkstations = Test-Connection -ComputerName $workstations -Count 1 -ea 4 |Select -Expand Address
#If they are not all online generate a file listing which ones are offline
If($workstations.count -gt $OnlineWorkstations.count){
    "Workstations not online:" | Set-Content C:\Scripts\Offline.txt
    $workstations | Where{$_ -notin $OnlineWorkstations} | Add-Content C:\Scripts\Offline.txt
}
#Get data from online workstations
$Results = ForEach ($workstation in $workstation) {
       Get-Service -ComputerName $workstation | where-object {$_.Name -eq 'xxx Agent'} | select displayname, name, starttype, status
}
$Results  |
    export-csv -Path C:\Scripts\therealdeal.c

此外,您的csv文件名似乎缺少' sv'来自扩展名。