Invok-Command on localhost not working

Gerd St 20 Reputation points
2023-05-05T06:11:00.71+00:00

i am trying to roll out user environment variables to a newly created user after its creation. to do this i want to do

Invoke-Command -ComputerName localhost -Credentials $credentials

however if i do so, i get an error message :

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

my full script i try to execute is this:

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

i already figured out that i have to start WinRM service at least on some machines so i can do it that way, but this has only brougt me to that error message...

Windows for business Windows Server User experience PowerShell
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,751 Reputation points
    2023-05-09T15:08:53.52+00:00

    Hello there,

    Invoke-command requires remoting, regardless of whether it's being invoked on local machine or a remote computer.

    Enable PSRemoting Service to Start Automatic

    on both host and remote machines

    Set-Service winrm -StartupType Automatic

    Start-Service winrm

    Enable PSREmoting on both host and remote machines

    EnablePSRemoting -Force

    Hope this resolves your Query !!

    --If the reply is helpful, please Upvote and Accept it as an answer--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.