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.

References:

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

Did this or another article help you? If you like and can afford it, you can buy me a coffee (3 EUR) ☕️ to support me in writing more posts. In case you would like to contribute more or I helped you directly via email or coding/troubleshooting session, you can opt to give a higher amount through the following links or adjust the quantity: 50 EUR, 100 EUR, 500 EUR. All links redirect to Stripe.