Share via


Set-ExecutionPolicy Fun

Hm, I'm surprised this isn't included Out-Of-The-Box.  Let's say I have a new deployment of machines and I need to set the ExecutionPolicy for each of them.  Now, assuming I'm a domain admin, I should be able to do it remotely:

Function Enable-PowerShell {

    param (

        [string]$computerName = $env:computerName,

        [string]$mode = 'Unrestricted'

    );

   

    $modeHash = @{

        'Unrestricted' = 'Unrestricted';

        'RemoteSigned' = 'RemoteSigned';

        'AllSigned' = 'AllSigned';

        'Restricted' = 'Restricted';

        'Default' = 'Default';

        'Bypass' =  'Bypass'

    };

   

    if (!$modeHash[$mode]) {

        Write-Warning ("-mode $mode is not valid. Valid modes are {0}" -f [string]::Join(", ", $modeHash.Keys));

        return $null;

    }

    $mode = $modeHash[$mode];

   

    trap { continue; }
     

    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computerName);

    if (!$reg) {

        Write-Warning "Unable to open remote registry on $computerName.";

        return $null;
    }

   

    $key = "SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell";

    $regKey= $reg.OpenSubKey($key, $true);

    if (!$regKey) {

        Write-Warning "Unable to open registry key $key on $computerName.";

        return $null;

    }

   

    $regkey.SetValue('ExecutionPolicy', $mode);

    if ($regkey.GetValue('ExecutionPolicy') -ne $mode) {

        Write-Waring "Unable to set PowerShell Execution Policy on $computerName to $mode";

         return $null;

    }

}