Run scriptblock as different user on local machine

I want to run a scriptblock ($commands) as a different user ($credential) on the same machine where the script runs.

I tried “Invoke-Command -Credential $Credential -ScriptBlock {$commands}”, but it appears that you have to specify -ComputerName when using -Credential.

The system is firewalled and I am not allowed to enable PS-remoting.

Is there a way to to accomplish this?

You can use Start-Process and call PowerShell.exe with -credentials and arguments ‘-c &{your commands}’

Or

Use Start-Job with Credentials and -ScriptBlock parameter.

you could use -cn $env:computername or -cn localhost in the invoke-command statement.

Just make sure that any variables you intend to pass are done as $using:<variable>

 

$name=“bob” would be pased as $using:name and not just $name