我需要將一些關于服務器的資訊保存到一個 csv 檔案中。將保存到此檔案的資訊將像回圈一樣添加,因此,在某種程度上,我需要將資訊附加到檔案中。
我嘗試了兩種方法來做到這一點,但它們似乎都不起作用(變數 ip、id、name 和 stauts,在腳本的最終版本中不會是靜態的):
添加內容
for($i=0; $i -lt 5; $i ){ $OutFile = "C:\information.csv" $test = Test-Path -Path $Outfile $id=$i $ip="1234$i" $name="Server$i" $status="up" if(!$test) { Add-Content -Path $Outfile -Value '"ID","IP","Name","Status"' }添加內容 -Path $OutFile -Value $id,$ip,$name,$status
}
當我運行此腳本時,所有資訊都放在同一列/標題中。

創建空 CSV 檔案并向其添加內容:
for($i=0; $i -lt 5; $i ){ $OutFile = "C:\information.csv" $test = Test-Path -Path $Outfile $id=$i $ip="1234$i" $name="Server$i" $status="up" if(!$test) { $newcsv = {} | Select "ID", "NAME","IP","STATUS" | Export-Csv $OutFile } $csvfile = Import-Csv $OutFile $csvfile.ID = $id $csvfile.NAME = $ip $csvfile.IP = $name $csvfile.STATUS = $status $csvfile | Export-CSV $outfile –Append }
當我運行這個腳本時,我會收到每個標頭的錯誤訊息:
在此物件上找不到屬性“ID”。驗證該屬性是否存在并且可以設定。
However, the file is created and the information is put in the correct header, but the content of each header is wrong, and the ID header has a different value from the variable that I created

I way bests suits to append values to a csv file, and what I' doing wrong to have the outputs shown in the pictures?
I'm available to respond to any question regarding this problem. Thank you for your time.
uj5u.com熱心網友回復:
要輸出有效的 CSV,請收集物件并使用Export-Csv.
嘗試這樣的事情:
$OutFile = "C:\information.csv"
# output 5 dummy servers
0..4 | ForEach-Object {
[PsCustomObject]@{
Id = $_
IP = "192.168.1.$_"
Name = "Server$_"
Status = 'Up'
}
} | Export-Csv -Path $Outfile -NoTypeInformation
顯示在螢屏上時的輸出:
Id IP Name Status
-- -- ---- ------
0 192.168.1.0 Server0 Up
1 192.168.1.1 Server1 Up
2 192.168.1.2 Server2 Up
3 192.168.1.3 Server3 Up
4 192.168.1.4 Server4 Up
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313621.html
標籤:powershell csv
