我有一個用于檢測 Log4j 的作業腳本,但試圖將所有結果匯出到 CSV。
當前腳本能夠匯出,但給了我多行精確結果。
$hostnames = "PC1"
foreach ($hostname in $hostnames){
Write-Host "Starting..."
$List = Invoke-Command -ComputerName $hostname {Get-ChildItem 'C:\' -Recurse -Force -Include *.jar -ea 0 | foreach {select-string "JndiLookup.class" $_} | select -exp Path}
if ($List -ne $null)
{
$List1 = [system.String]::Join("`r`n", $List)
$file_location = "C:\Powershell\log4j-test.csv"
$global:name = @{N="Computer Name";E={$hostname}}
$global:lists = @{N="Affected Location";E={$List1}}
Write-Host "Done.."
$name, $lists | Export-CSV $file_location -noTypeInformation -Force -Append -Encoding UTF8
}
}
uj5u.com熱心網友回復:
你可能正在尋找這樣的東西:
[pscustomobject] @{
'Computer Name' = $hostname
'Affected Location' = $List -join "`r`n"
} | Export-CSV $file_location -noTypeInformation -Force -Append -Encoding UTF8
請注意,由于在列中使用換行符 ( ) 作為分隔符,因此在每次迭代中創建的每個 CSV 行(可能)將跨越多行。"`r`n"Affected Location
至于你嘗試了什么:
您的哈希表文字(例如
@{N="Computer Name";E={$hostname}})使用計算屬性的語法,但您沒有使用 cmdlet - 通常Select-Object- 能夠創建計算屬性。更一般地,
Export-Csv并ConvertTo-Csv在Windows PowerShell中也沒有有意義的支持哈希表作為輸入物件-你需要提供[pscustomobject]由鑄造改為實體,您可以輕松地創建[1]到Hashtable的文字[pscustomobject],如上圖所示,- 相比之下,在PowerShell (Core) 7 中,您現在可以直接使用哈希表作為輸入,盡管您可能希望使用
[ordered]哈希表進行可預測的列排序。
- 相比之下,在PowerShell (Core) 7 中,您現在可以直接使用哈希表作為輸入,盡管您可能希望使用
[1] 嚴格來說,表單[pscustomobject] @{ ... }不是cast,而是用于將實體創建為文字的內置語法糖[pscustomobject]。事實證明,在這種情況下,哈希表文字中的鍵定義順序得到維護,而它不是在獨立的哈希表文字中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/402175.html
上一篇:替換文本欄位中不必要的雙引號
