Running commands in a specific user context in PowerShell

1 minute read

If you find yourself in a limited cmd shell but have obtained credentials for another user, you can leverage PowerShell’s Invoke-Command cmdlet to execute a script block in the security context of that specific user. This can be helpful in a penetration test setting or CTF.

One thing to be aware of is that you cannot just pass a user and password string to the -Credential parameter of Invoke-Command, but need to create a valid PSCredential object first.

While the Get-Credential cmdlet can give you such an object, it’s unlikely that you can get prompted given your current access. To work around this, you can create a PSCredential yourself and pass it to Invoke-Command.

A fully functional one-liner (here, just reading a file) could look like this:

powershell.exe -c "$user='WORKGROUP\John'; $pass='password123'; try { Invoke-Command -ScriptBlock { Get-Content C:\Users\John\Desktop\secret.txt } -ComputerName Server123 -Credential (New-Object System.Management.Automation.PSCredential $user,(ConvertTo-SecureString $pass -AsPlainText -Force)) } catch { echo $_.Exception.Message }" 2>&1

I like to add a try {} catch {} and a redirect from of stderr to stdout (2>&1) to be able to see errors as most limited shells wouldn’t give you the stderr output otherwise.


Like to comment? Feel free to send me an email or reach out on Twitter.