Powershell脚本错误 - 无法验证参数'Property'的参数:无法索引到空数组

问题描述 投票:1回答:1

我在本文中找到了一个Powershell脚本:How to detect applications using "hardcoded" DC name or IP

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

有人能帮忙吗?

powershell null powershell-v4.0
1个回答
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并导致整个子表达式返回$null时,它会悄悄地忽略这种情况。 另请注意如何将哈希表文字(@{ ... })直接转换为类型加速器[pscustomobject],以便将其转换为自定义对象。

[1]注意,因为PSv3,试图索引非$null但也不是数组的值不会失败,但悄然返回$null;例如:$v=20; $v[1] # -> $null。 索引到字符串值是一种特殊情况,但是:它返回指定位置的字符:$v='hi'; $v[1] # -> 'i'

© www.soinside.com 2019 - 2024. All rights reserved.