Wednesday, 28 May 2014

Update the PowerShell Execution Policy to allow the running of remote scripts

Open a PowerShell window as an Administrator and run the command below on the target machine(enter ‘y’ at the prompt):

Set-ExecutionPolicy RemoteSigned

This will set the machine to require signing for remote scripts only.

Note that the user running the scripts must be a member of the Administrators Group on the remote machines.

This can be laborious if you're managing many servers so a quick ProcMon suggests that all this is doing is setting the registry entry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"ExecutionPolicy"="RemoteSigned"

This allowed me to update my servers using:


# Prompt for the relevant credentials
$credentials = Get-Credential -ErrorAction Stop

if(!$credentials) {
  exit 1
}

$registryPath="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell"

"Server1","Server2","Server3" |% {
  $server="$_.emb.co.uk"
  
  # Enter-PSSession -ComputerName $server -Credential $credentials
  $session = New-PSSession -ComputerName $server -Credential $credentials
  
  Invoke-Command -Session $session -ArgumentList $server, $registryPath -ScriptBlock {
    $server = $args[0]
    $registryPath = $args[1]
    
    $property = Get-ItemProperty -Name ExecutionPolicy -Path $registryPath
    
    # Set the value to be one of Unrestricted | RemoteSigned | AllSigned | Restricted | Bypass
    Set-ItemProperty -Value RemoteSigned -Name ExecutionPolicy -Path $registryPath
    
    echo ("${server}: ExecutionPolicy was '{0}' and is now '{1}" -f $property.ExecutionPolicy, (Get-ItemProperty -Name ExecutionPolicy -Path $registryPath).ExecutionPolicy)
    } 
  
  Remove-PSSession $session
}

No comments: