3

我正在创建一个批处理文件,其中涉及将 SID 转换为本地/域用户名。由于我们无法使用命令提示符实现这一点,因此我计划使用 powershell,并且我也有 PS 命令。我可以在 powershell 控制台中运行它而没有任何问题,但不确定如何在命令提示符下将其用作单行(在批处理文件中使用)。我已经尝试过以下方法。

在 PS 控制台中完美运行的 Powershell 命令 -

([System.Security.Principal.SecurityIdentifier]("S-1-5-32-544")).Translate([System.Security.Principal.NTAccount]).Value

我已经尝试过但没有成功的命令行 -

powershell -command ([System.Security.Principal.SecurityIdentifier]("S-1-5-32-544")).Translate([System.Security.Principal.NTAccount]).Value

powershell -command {([System.Security.Principal.SecurityIdentifier]("S-1-5-32-544")).Translate([System.Security.Principal.NTAccount]).Value}

我究竟做错了什么?是由于任何转义字符还是我缺少任何 powershell 命令参数?任何帮助是极大的赞赏。

4

4 回答 4

3

这是一个简短的 VBScript 脚本,它使用 WMI 为您进行转换:

Dim SID
SID = WScript.Arguments.Item(0)

Dim SWbemServices, SWbemObject
Set SWbemServices = GetObject("winmgmts:root/CIMV2")
Set SWbemObject = SWbemServices.Get("Win32_SID.SID='" & SID & "'")
WScript.Echo SWbemObject.ReferencedDomainName & "\" & SWbemObject.AccountName

您当然需要从您的 shell 脚本(批处理文件)中捕获此脚本的输出。

于 2014-07-22T20:50:07.277 回答
3
powershell -command "([System.Security.Principal.SecurityIdentifier]('S-1-5-32-544')).Translate([System.Security.Principal.NTAccount]).Value"

为我工作。只是将最里面的双引号更改为 SID 周围的单引号的问题。

或者,用反斜杠转义它们

powershell -command "([System.Security.Principal.SecurityIdentifier](\"S-1-5-32-544\")).Translate([System.Security.Principal.NTAccount]).Value"
于 2014-07-23T03:14:14.870 回答
2

你真的很亲近。你想要做的是:

powershell -command "& {([System.Security.Principal.SecurityIdentifier]('S-1-5-32-544')).Translate([System.Security.Principal.NTAccount]).Value}"

我使用Get-WmiObjectcmdlet 对此进行了测试。在标准但提升的 cmd shell 中,我输入了:

powershell -command "& {get-wmiobject win32_operatingsystem}"

此时,powershell 返回的 wmi 对象数据已写入控制台。您还可以将命令加载到变量中,如下所示:

set wmi=powershell -command "& {get-wmiobject win32_operatingsystem}"

如果您调用该变量%wmi%,则在打印之前会有延迟。命令本身在变量中,因此每次调用变量时,它都会执行 powershell 代码并返回结果。

于 2014-07-22T19:56:32.823 回答
1

另一种答案是使用 base64 编码的命令开关。

@ECHO OFF
powershell -encodedcommand "KABbAFMAeQBzAHQAZQBtAC4AUwBlAGMAdQByAGkAdAB5AC4AUAByAGkAbgBjAGkAcABhAGwALgBTAGUAYwB1AHIAaQB0AHkASQBkAGUAbgB0AGkAZgBpAGUAcgBdACgAIgBTAC0AMQAtADUALQAzADIALQA1ADQANAAiACkAKQAuAFQAcgBhAG4AcwBsAGEAdABlACgAWwBTAHkAcwB0AGUAbQAuAFMAZQBjAHUAcgBpAHQAeQAuAFAAcgBpAG4AYwBpAHAAYQBsAC4ATgBUAEEAYwBjAG8AdQBuAHQAXQApAC4AVgBhAGwAdQBlAA=="
PAUSE

解码后,您会看到它是 OP 的原始片段(保留了双引号)。可能对 OP 来说有点矫枉过正,但对具有较大脚本的开发人员很有用。加上我原来的答案和其他人一样,所以我不得不编辑。

powershell.exe -EncodedCommand

Accepts a base-64-encoded string version of a command. Use this parameter
to submit commands to Windows PowerShell that require complex quotation
marks or curly braces.
于 2014-07-23T03:44:48.193 回答