我正在嘗試將我的 CSV 檔案轉換為具有某種表格格式和樣式的 Excel 檔案,但由于某種原因,我收到“無法索引到空陣列”的訊息。如果我能得到任何幫助或建議,我將不勝感激。謝謝
function Convert-to-Excel{
$params = @{
AutoSize = $true
TableStyle = 'Medium6'
BoldTopRow = $true
WorksheetName = 'Audit Log'
PassThru = $true
Path = "C:\AuditLogSearch\$((Get-Date).AddDays(-7).ToString('yyyy-MM-dd')) _ $(Get-Date -Format "yyyy-MM-dd") Audit-Log-Records11.xlsx"
}
$modifiedFile = Import-Csv "C:\AuditLogSearch\Modified-Audit-Log-Records.csv"
$actionReference = Import-Csv "C:\AuditLogSearch\Reference\Action.csv"
$xlsx = foreach ($u in $modifiedFile) {
$u.User = (Get-AzureADUser -ObjectId $u.User).DisplayName
New-Object PsObject -Property @{
User = $u.User
"Search Criteria" = $u."Search Criteria"
"Result Status" = $u."Result Status"
"Date & Time" = $u."Date & Time"
"Type of Action" = if (($actionReference | where-object { $_.Name -eq $u."Type of Action" }).Value -ne $null) { ($actionReference | where-object { $_.Name -eq $u."Type of Action" }).Value }
else { $u."Type of Action" }
} | Export-Excel @params
$ws = $xlsx.Workbook.Worksheets[$params.Worksheetname]
$ws.View.ShowGridLines = $false # => This will hide the GridLines on your file
Close-ExcelPackage $xlsx
}
}

uj5u.com熱心網友回復:
您在回圈的第一次迭代時關閉 Excel 包,因此為什么當它進入下一次時,它會嘗試執行以下操作:
$null[$null] # => InvalidOperation: Cannot index into a null array
嘗試修改您的函式,使其看起來像這樣:
- 首先,構建
object[]:
$result = foreach ($u in $modifiedFile) {
$u.User = (Get-AzureADUser -ObjectId $u.User).DisplayName
New-Object PsObject -Property @{
User = $u.User
"Search Criteria" = $u."Search Criteria"
"Result Status" = $u."Result Status"
"Date & Time" = $u."Date & Time"
"Type of Action" = if (($actionReference.........
else { $u."Type of Action" }
}
}
- 然后將其匯出到 Excel:
$xlsx = $result | Export-Excel @params
$ws = $xlsx.Workbook.Worksheets[$params.Worksheetname]
$ws.View.ShowGridLines = $false # => This will hide the GridLines on your file
Close-ExcelPackage $xlsx
有一點要注意,PassThru = $true在$params意味著,而不是保存Excel中直接我們要保存對“進一步處理”一個變數,并通過進一步操縱我的意思是,在這種情況下,物件,隱藏作業表的網格線($ws.View.ShowGridLines = $false)然后關閉包(將其存盤在磁盤上)。
如果您不需要對作業表執行任何修改,您可以完全洗掉PassThru并執行以下操作:
$result | Export-Excel @params
這將關閉包并將 Excel 存盤在您的磁盤上。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/372229.html
標籤:电源外壳 文件 powershell-2.0
