function Enable-PSRemotingRemotely() { param( ## The computer on which to enable remoting $Computername, ## The credential to use when connecting $Credential = (Get-Credential) ) Set-StrictMode -Version Latest $VerbosePreference = "Continue" $credential = Get-Credential $credential $username = $credential.Username $password = $credential.GetNetworkCredential().Password $script = @" `$log = Join-Path `$env:TEMP Enable-RemotePsRemoting.output.txt `$scriptFile = Join-Path `$env:TEMP tmpScriptFile.ps1 Remove-Item -Force `$log -ErrorAction SilentlyContinue Remove-Item -Force `$scriptFile -ErrorAction SilentlyContinue Start-Transcript -Path `$log ## Create a task that will run with full network privileges. ## In this task, we call Enable-PsRemoting 'Enable-PSRemoting -Force' | Out-File `$scriptFile -Force schtasks /CREATE /TN 'Enable Remoting' /SC WEEKLY /RL HIGHEST /RU SYSTEM /TR "powershell.exe -executionpolicy bypass -command `$scriptFile" /F | Out-String schtasks /RUN /TN 'Enable Remoting' | Out-String `$securePass = ConvertTo-SecureString $password -AsPlainText -Force `$credential = New-Object Management.Automation.PsCredential $username,`$securepass ## Wait for the remoting changes to come into effect for(`$count = 1; `$count -le 10; `$count++) { `$output = Invoke-Command localhost { 1 } -Cred `$credential -ErrorAction SilentlyContinue if(`$output -eq 1) { Write-Host "Done!!!"; break; } Write-Host "Attempt `$count : Not ready yet.`n" Sleep 5 } ## Delete the temporary task schtasks /DELETE /TN 'Enable Remoting' /F | Out-String Stop-Transcript "@ $commandBytes = [System.Text.Encoding]::Unicode.GetBytes($script) $encoded = [Convert]::ToBase64String($commandBytes) Write-Verbose "Configuring $computername" $command = "powershell -NoProfile -EncodedCommand $encoded" $null = Invoke-WmiMethod -Computer $computername -Credential $credential ` Win32_Process Create -Args $command ## Wait for the remoting changes to come into effect for($count = 1; $count -le 10; $count++) { $output = Invoke-Command $Computername { 1 } -Cred $credential -ErrorAction SilentlyContinue if($output -eq 1) { Write-Host "Done!!!"; break; } Write-Host "Attempt $count : Not ready yet." Sleep 5 } Write-Verbose "Testing connection" Invoke-Command $computername { Get-WmiObject Win32_ComputerSystem } -Credential $credential }