小编Plu*_*ang的帖子

“New-Object WindowsPrincipal([WindowsIdentity]::GetCurrent())”和“[WindowsPrincipal] [WindowsIdentity]::GetCurrent()”之间的区别

我正在尝试检查 Powerhell 脚本是否以管理员身份运行。在网上搜索后,我得到了一些运行良好的示例代码。
为了获取该WindowsPrincipal对象,我找到了两个示例代码,如下所示。

第一的:

New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
Run Code Online (Sandbox Code Playgroud)

第二:

[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
Run Code Online (Sandbox Code Playgroud)

第二个让我很困惑。

根据此页面,我知道这[ ]是一个强制转换运算符。根据此页面,PowerShell 是基于 .NET Framework 构建的。在我看来,这意味着上述两个PowerShell脚本可以转换为C#。
所以我尝试一下。
当我将第一个 PowerShell 脚本转换为 C# 时。它工作正常,如下所示。

## First PowerShell script
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())

// C#
var wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将第二个 PowerShell 脚本转换为 C# 时。我收到编译错误。IDE 告诉我WindowsIdentity不能转换为WindowsPrincipal.

## Second PowerShell script
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()

// both C# code below cause compile error
var wp = System.Security.Principal.WindowsIdentity.GetCurrent() as System.Security.Principal.WindowsPrincipal;
var wp2 = (System.Security.Principal.WindowsPrincipal)System.Security.Principal.WindowsIdentity.GetCurrent();
Run Code Online (Sandbox Code Playgroud)

正如我在C#上尝试的那样,System.Security.Principal.WindowsIdentity …

powershell

4
推荐指数
1
解决办法
3278
查看次数

标签 统计

powershell ×1