Invoke-Command on localhost not working

Gerd St 20 Reputation points

I am using powershell to roll out a complete set of users, applications and servers to new server machines, for our software we require some environment variables to be set in the runtime users context. to do so, i wanted to run a bash script that rolls out the EnvVars but this must be done by the user himself. So i thought i could just run this by using Invoke-Command ComputerName localhost... but this always results in an error message:

[localhost] Beim Verbinden mit dem Remoteserver "localhost" ist folgender Fehler aufgetreten: Zugriff verweigert Weitere Informationen finden Sie im Hilfethema 
    + CategoryInfo          : OpenError: (localhost:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken

(sorry, thats a german machine in that case)

this is the script sniplet i try to use:

Write-Host seting up Environment
$usernameIA = "NameOfUser"
$password = 'ThePassword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($usernameIA, $securePassword)
Invoke-Command -ComputerName localhost -Credential $credential -ScriptBlock $ScriptBlock

where the User has been just created a bit earlier in the script, so it has not yet been loggen on.

i have read somewhere that it works with PS7, but i can not always update to PS7 and have to go ith built in PS5 due to these production machines do not have access to the internet.

am i doing somethjing wrong or am i missing something? is there a better way to roll out environment variables to the newly created users?

A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,300 questions
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 32,726 Reputation points

    Don't use Invoke-Command, just launch a separate powershell process with the users credentials.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 45,671 Reputation points

    Assuming you want to set those environment variables so they persist, you can use this in the PowerShell script:


    You can add a 3rd parameter to control which set of environment variables (Machine, Process, or User).

    1 person found this answer helpful.
    0 comments No comments