如何修复PowerShell中无法索引到空数组 [英] How to fix Cannot index into a null array in PowerShell
本文介绍了如何修复PowerShell中无法索引到空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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:AuditLogSearchModified-Audit-Log-Records.csv"
$actionReference = Import-Csv "C:AuditLogSearchReferenceAction.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
}
}
推荐答案
您在循环的第一次迭代中关闭了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
需要注意的一点是,$params
上的PassThru = $true
意味着我们不是直接保存Excel,而是希望将对象保存在一个变量上,以便进行进一步的操作,我的进一步操作的意思是,在这种情况下,隐藏工作表的网格线($ws.View.ShowGridLines = $false
),然后关闭包(将其存储在磁盘上)。
如果您不需要对工作表执行任何修改,只需完全删除PassThru
并执行以下操作:
$result | Export-Excel @params
这将关闭包并将Excel存储在您的磁盘上。
这篇关于如何修复PowerShell中无法索引到空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文