2017-04-13 78 views
1

我是PowerShell新手,正在創建一個小腳本,用於從文本文件中導入筆記本電腦和工作站列表,查看它們是否在我們的網絡上並繼續檢查計算機的代理狀態/配置。If Else Statement with String,導出爲CSV

如果電腦不在線,我想有一個文件說$工作站不在線。

我遇到的問題是使用其他數據將該失敗字符串獲取到一個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 
+3

嘗試更改爲複數以避免變量混淆可能?> $ workstations = Get-content' then($工作站在$ workstations中)'不是100%,但我理解問題。 –

回答

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'。

+0

非常感謝!我爲此學到了很多東西。看起來你正在比較兩個列表的數量,並基於此創建兩個單獨的列表 – MrDoe