2016-08-23 27 views
1

我运行了本文中找到的Powershell脚本:How to detect applications using "hardcoded" DC name or IPPowershell脚本错误 - 无法验证参数“属性”上的参数:无法索引到空数组中

The code is as follows:

Get-WinEvent -ComputerName dc01.contoso.com -MaxEvents 1000 -FilterHashtable @{LogName="Directory Service" ; ID=1139 } | ForEach-Object ` 
{ 
$_info = @{ 
"Operation" = [string] $_.Properties.Value[0] 
"User" = [string] $_.Properties.Value[2] 
"IP:Port" = [string] $_.Properties.Value[3] 
} 
New-Object psobject -Property $_info 
} 

我收到的错误是:

New-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. 
At C:\scripts\HideDC.ps1:9 char:37 
+  New-Object psobject -Property <<<< $_info  
    + CategoryInfo   : InvalidData: (:) [New-Object], 
ParameterBindingValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewObjectCommand 

Cannot index into a null array. 
At C:\scripts\HideDC.ps1:5 char:55 
+   "Operation" = [string] $_.Properties.Value[ <<<< 0] 
    + CategoryInfo   : InvalidOperation: (0:Int32) [], RuntimeException 
    + FullyQualifiedErrorId : NullArray 

任何人都可以在这方面帮助?

+2

安置自己的代码有问题:它在指定的位置返回字符。不要使用图片作为代码。 – Fairy

+1

调试代码,在循环内的PowerShell ISE中设置一个断点并检查变量值。 – wOxxOm

回答

0

TL;博士

Get-WinEvent -ComputerName dc01.contoso.com -MaxEvents 1000 -FilterHashtable @{ 
    LogName="Directory Service" ; ID=1139 } | 
    ForEach-Object { 
     [pscustomobject] @{ 
     "Operation" = $(try { [string] $_.Properties.Value[0] } catch {}) 
     "User" =  $(try { [string] $_.Properties.Value[2] } catch {}) 
     "IP:Port" = $(try { [string] $_.Properties.Value[3] } catch {}) 
     } 
    } 

  • Cannot index into a null array错误消息告诉您$_.Properties.Value$null而非阵列,所以访问此非数组的元素的尝试失败[1]

这意味着至少有一些事件日志记录没有嵌入数据值。

  • (该New-Object : Cannot validate argument on parameter 'Property'仅仅是一个后续错误抱怨有-Property变元为$null,因为初始错误引起$_info$null。)

    • 最简单的解决方案是使用子表达式运算符($(...))与嵌入式try { ... } catch {}处理程序包含$_.Properties.Value[<n>]引用,它悄然忽略$_.Properties.Value$null和c点击整个子表达式返回$null

    • 另请注意,如何将散列表文字(@{ ... })直接转换为键入加速器[pscustomobject]以便将其转换为自定义对象。


[1]注意,由于PSv3,试图索引即非$null但也不是数组值不失败,但静静返回$null;例如:$v=20; $v[1] # -> $null
索引到一个字符串值是一个特殊情况,但是:$v='hi'; $v[1] # -> 'i'

相关问题