如何正确地在PowerShell中pipe道对象,以避免“expression式只允许作为pipe道的第一个元素”的错误

有没有办法做到以下几点,而不创build对象$ obj?

$obj = New-Object System.Security.Principal.NTAccount("Students") ; $obj.Translate([System.Security.Principal.SecurityIdentifier]).Value 

我曾经尝试过,像这样:

 New-Object System.Security.Principal.NTAccount("Students") | $_.Translate([System.Security.Principal.SecurityIdentifier]).Value 

但有以下错误:

 Expressions are only allowed as the first element of a pipeline. At line:1 char:128 + New-Object System.Security.Principal.NTAccount("Students") | $_.Translate([System.Security.Principal.SecurityIdentifi er]).Value <<<< + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline 

提前致谢!

 $(New-Object System.Security.Principal.NTAccount("Students")).Translate([System.Security.Principal.SecurityIdentifier]).Value 

如果您想坚持使用pipe道,请使用ForEach-Object cmdlet。

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