在命令行/批处理文件中运行Powershell命令

时间:2014-07-22 19:02:32

标签: batch-file powershell command-line scripting sid

我正在创建一个批处理文件,涉及将SID转换为本地/域用户名。由于我们无法使用命令提示符实现此功能,因此我计划使用powershell,并且我也有PS命令。我能够在powershell控制台中运行它没有任何问题,但不知道如何在命令提示符中使用它作为单行(在批处理文件中使用它)。我已经尝试了下面的内容。

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

([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 个答案:

答案 0 :(得分: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"

答案 1 :(得分:2)

这是一个简短的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脚本(批处理文件)中捕获此脚本的输出。

答案 2 :(得分:1)

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

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

我使用Get-WmiObject cmdlet对此进行了测试。在我输入的标准但高架的cmd shell中:

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

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

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

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

答案 3 :(得分:1)

另一个答案是使用base64 encoded命令开关。

@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.