繁体   English   中英

Powershell 在循环中找不到新对象构造函数

[英]Powershell New-Object Constructor was not found within loop

我正在努力使用下面的代码。 我正在尝试通过 powershell 将安全事件日志放入一个数组并仅选择我感兴趣的值。下一步我想遍历这个数组并将这些值写入人类可读的日志中。 除了将 SID 转换为循环中的帐户名称之外,一切都很好地结合在一起。

这就是我正在做的事情:

$eventID = 4732

$log = @( Get-EventLog -LogName security -InstanceId $eventID | Select-Object -Property EventID,EntryType,TimeGenerated,
            @{n="AccountName";e = {$_.replacementstrings[1]}},
            @{n="GroupName";e = {$_.replacementstrings[2]}},
            @{n="AdminName";e = {$_.replacementstrings[6]}}
            @{n="DomainName";e = {$_.replacementstrings[3]}}
        )

在此之后,我想将从事件日志中获得的 SID 转换为实际的帐户名。 我通过遍历所有条目并将它们发送到 output 来做到这一点。

$log | ForEach-Object {  

    ((New-Object System.Security.Principal.SecurityIdentifier ($_.AccountName)).Translate( [System.Security.Principal.NTAccount])).Value
}

Output 我得到的是实际验证的帐户名,它告诉我代码有效。 除了它还给我以下错误:

New-Object : A constructor was not found. Cannot find an appropriate constructor for type System.Security.Principal.Sec
urityIdentifier.
At line:3 char:3
+ ((New-Object System.Security.Principal.SecurityIdentifier ($_.Account ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

最奇怪的部分是当我在循环之外调用代码时,它可以工作:

((New-Object System.Security.Principal.SecurityIdentifier ($log.AccountName[0])).Translate( [System.Security.Principal.NTAccount])).Value

但由于我不知道数组将有多少条目,我需要它在循环中工作。 难道我做错了什么?

我知道可能有更多方法可以做到这一点,但我只想了解它发生了什么以及为什么会发生。 感谢任何能提供帮助的人。

您的@()没用,但这不会导致错误, Get-EventLog已经将结果检索到数组中。

您忘记了行尾的昏迷@{n="AdminName";e = {$_.replacementstrings[6]}}

$eventID = 4732

$log = Get-EventLog -LogName security -InstanceId $eventID | Select-Object -Property EventID,EntryType,TimeGenerated,
        @{n="AccountName";e = {$_.replacementstrings[1]}},
        @{n="GroupName";e = {$_.replacementstrings[2]}},
        @{n="AdminName";e = {$_.replacementstrings[6]}},
        @{n="DomainName";e = {$_.replacementstrings[3]}}

$log | ForEach-Object {  
    ((New-Object System.Security.Principal.SecurityIdentifier($_.AccountName)).Translate([System.Security.Principal.NTAccount])).Value
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM