簡體   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