Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Powershell command in a command line/batch file

I am creating a batch file which involves converting a SID to local/domain username. Since we can not achieve this using the command prompt I am planning to use powershell and I have the PS command as well. I am able to run it in powershell console without any issue, but not sure how to use it in command prompt as a SINGLE LINE(to use it in batch file). I have already tried the below.

Powershell command which works perfectly in PS console -

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

Command lines which I have already tried but with no success -

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}

What am I doing wrong? Is it due to any escape characters or am I missing any powershell command parameters? Any help is greatly appreciated.

like image 551
gbabu Avatar asked Sep 16 '26 02:09

gbabu


2 Answers

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

worked for me. Just a question of changing the innermost double-quotes to singles around the SID.

Alternatively, escape them with a backslash

powershell -command "([System.Security.Principal.SecurityIdentifier](\"S-1-5-32-544\")).Translate([System.Security.Principal.NTAccount]).Value"
like image 149
andyb Avatar answered Sep 19 '26 01:09

andyb


Here is a short VBScript script that uses WMI to do the conversion for you:

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

You would of course need to capture this script's output from your shell script (batch file).

like image 34
Bill_Stewart Avatar answered Sep 19 '26 02:09

Bill_Stewart