Set executionpolicy windows powershell updated your execution policy successfully

По-умолчанию настройки Windows запрещают запуск скриптов PowerShell. Это необходимо для предотвращения запуска вредоносного кода на PowerShell. Настройки

По-умолчанию настройки Windows запрещают запуск скриптов PowerShell. Это необходимо для предотвращения запуска вредоносного кода на PowerShell. Настройки политик запуска PowerShell скриптов определяются в Execution Policy. В этой статье мы рассмотрим доступные политики запуска PS скриптов, как изменить Execution Policy и настроить политики использования PowerShell скриптов на компьютерах в домене.

Содержание:

  • Выполнение PowerShell скриптов запрещено для данной системы
  • Как разрешить запуск скриптов PowerShell с помощью Execution Policy?
  • Настройка PowerShell Execution Policy с помощью групповых политик
  • Способы обхода политики PowerShell Execution

Выполнение PowerShell скриптов запрещено для данной системы

При попытке выполнить PowerShell скрипт (файл с расширением PS1) на чистой Windows 10, появляется ошибка:

File C:ps.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
Не удается загрузить файл.ps1, так как выполнение скриптов запрещено для данной системы.

Не удается загрузить файл ps1, так как выполнение скриптов запрещено для данной системы.

Текущее значение политики выполнения скриптов PowerShell на компьютере можно получить командой:

Get-ExecutionPolicy

Get-ExecutionPolicy

Доступны следующие значения PowerShell Execution Policy:

  • Restricted – запрещен запуск скриптов PowerShell, можно выполнять только интерактивные команды в консоли;
  • AllSigned – разрешено выполнять только подписанные PS скрипты с цифровой подписью от доверенного издателя (можно подписать скрипт самоподписанным сертификатом и добавить его в доверенные). При запуске недоверенных скриптов появляется предупреждение:
    Do you want to run software from this untrusted publisher? File .ps1 is published by CN=test1 and is not trusted on your system. Only run scripts from trusted publishers

    вы хотите запустить powershell скрипт от недоверенного издателя?

  • RemoteSigned – можно запускать локальные PowerShell скрипты без ограничения. Можно запускать удаленные PS файлы с цифровой подписью (нельзя запустить PS1 файлы, скачанные из Интернета, запущенные из сетевой папки по UNC пути и т.д.);
  • Unrestricted – разрешен запуск всех PowerShell скриптов;

    При запуске сторонних PowerShell скриптов может появляется предупреждение с подтверждением запуска, см. ниже.

  • Bypass – разрешён запуск любых PS файлов (предупреждения не выводятся) – эта политика обычно используется для автоматического запуска PS скриптов без вывода каких-либо уведомлений (например при запуске через GPO, SCCM, планировщик и т.д.) и не рекомендуется для постоянного использования;
  • Default – сброс настроек выполнения скриптов на стандартную;

    В Windows 10 значение политики выполнения PowerShell по-умолчанию Restricted, а в Windows Server 2016 — RemoteSigned.

  • Undefined – не задано. Применяется политика Restricted для десктопных ОС и RemoteSigned для серверных.

Как разрешить запуск скриптов PowerShell с помощью Execution Policy?

Чтобы изменить текущее значение политики запуска PowerShell скриптов, используется командлет Set-ExecutionPolicy.

Например, разрешим запуск локальных скриптов:

Set-ExecutionPolicy RemoteSigned

Подтвердите изменение политики запуска PS1 скриптов, нажав Y или A.

Set-ExecutionPolicy RemoteSigned разрешить запуск локальных powershell скриптов

Чтобы запрос не появлялся, можно использовать параметр Force.

Set-ExecutionPolicy RemoteSigned –Force

Если вы установили значение политики PowerShell Execution Policy в Unrestricted, то при запуске удаленных скриптов из сетевых каталогов по UNC пути, скачанных из интернета файлов, все равно будет появляться предупреждение:

Security warning
Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the
Unblock-File cmdlet to allow the script to run without this warning message.
Do you want to run?
[D] Do not run [R] Run once [S] Suspend [?] Help (default is "D")

Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning message

Как PowerShell различает локальные и удаленные скрипты? Все дело в идентификаторе зоны ZoneId, которую выставляет браузер в альтернативном потоке при загрузке файла (см. статью “Как Windows определяет, что файл скачан из Интернета?”). Вы можете разблокировать такой файл, поставив галку “Разблокирвать” в его свойствах или очиститься метку зоны с помощью комадлета Unblock-File.

Также следует различать различные области действия политик выполнения скриптов PowerShell (scopes):

  • MachinePolicy – действует для всех пользователей компьютера, настраивается через GPO;
  • UserPolicy – действует на пользователей компьютера, также настраивается через GPO;
  • Process — настройки ExecutionPolicy действует только для текущего сеанса PowerShell.exe (сбрасываются при закрытии процесса);
  • CurrentUser – политика ExecutionPolicy применяется только к текущему пользователю (параметр из ветки реестра HKEY_CURRENT_USER);
  • LocalMachine – политика для всех пользователей компьютера (параметр из ветки реестра HKEY_LOCAL_MACHINE);

Область применения политики можно указать с помощью параметр Scope командлета Set-ExecutionPolicy. Например:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass –Force

Проверим текущие настройки ExecutionPolicy для всех областей:

Get-ExecutionPolicy -List

Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Bypass
CurrentUser Undefined
LocalMachine RemoteSigned

Get-ExecutionPolicy scopes области действия

Значение политики выполнения, которые вы задаете с помощью командлета Set-ExecutionPolicy для областей CurrentUser и LocalMachine, хранятся в реестре. Например, выполните командлет:

Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Restricted –Force

Откройте ветку реестра HKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell и проверьте значение REG_SZ параметра ExecutionPolicy. Оно изменилось на Restricted (допустимые значения параметра Restricted, AllSigned, RemoteSigned, Bypass, Unrestricted и Undefined).

ExecutionPolicy в реестре

Аналогичные настройки для области CurrentUser находятся в разделе реестра пользователя HKEY_CURRENT_USERSOFTWAREMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell.

Отметим, что чаще всего в корпоративной среде используется ExecutionPolicy со значением AllSigned на уровне LocalMachine. Это обеспечивает максимальный баланс между безопасностью и удобством. Для личного пользования на компьютере можно использовать RemoteSigned. Ну а Bypass политику лучше использовать только для запуска отдельных задач (например для запуска скриптов через GPO или заданий планировщика).

Настройка PowerShell Execution Policy с помощью групповых политик

Вы можете настроить политику выполнения PowerShel скриптов на серверах или компьютерах домена с помощью групповых политик.

  1. С помощью редактора доменных GPO (gpmc.msc) создайте новую GPO (или отредактируйте) существующую и назначьте ее на OU с компьютерами, к которым нужно применить политику запуска PowerShell скриптов;
  2. В редакторе политики перейдите в раздел Computer Configuration -> Policies -> Administrative Templates -> Windows Components -> Windows PowerShell и найдите политику Turn on Script Execution (Включить выполнение сценариев);

    Аналогичная политика есть в пользовательском разделе GPO — User Configuration, но политика компьютера имеет приоритет.

  3. Для политики доступны три значения:
    • Allow only signed scripts (Разрешать только подписанные сценарии) — соответствует политике AllSigned;
    • Allow local scripts and remote signed scripts (Разрешать локальные и удаленные подписанные сценарии) — соответствует политике PS RemoteSigned;
    • Allow all scripts (Разрешать все сценарии) — политика Unrestricted. групповая политика Turn on Script Execution
  4. Выберите необходимое значение политики, сохраните GPO и обновите политики на компьютере.
  5. Проверьте, что для области MachinePolicy теперь действуют новые настройки выполнения. политка executionpolicy настроена через ПЗЩ

После настройки политики выполнения через GPO вы не сможете изменить настройки политики выполнения скриптов вручную. При попытке изменить настройки Execution Policy на компьютере, на который применяется такая GPO, появится ошибка:

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings.

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope

Способы обхода политики PowerShell Execution

Есть несколько трюков, которые могут помочь вам, когда нужно запустить на компьютере PowerShell скрипт, не изменяя настройки политики выполнения. Например, я хочу запустить простой PS1 скрипт, который поверяет, что запущен с правами администратора.

Можно с помощью Get-Content получить содержимое скрипта и перенаправить его в стандартныq поток ввода консоли PS.

Get-Content c:pscheck_process_elevation.ps1 | PowerShell.exe -noprofile –

Либо можно запустить новый процесс powershell.exe с политикой выполнения Bypass:

powershell.exe -noprofile -executionpolicy bypass -file c:pscheck_process_elevation.ps1

обход действия powershell execution политики

The error message indicates that the setting you’re trying to define via Set-ExecutionPolicy is overridden by a setting in another scope. Use Get-ExecutionPolicy -List to see which scope has which setting.

PS C:> Get-ExecutionPolicy -List

        Scope    ExecutionPolicy
        -----    ---------------
MachinePolicy          Undefined
   UserPolicy          Undefined
      Process          Undefined
  CurrentUser          Undefined
 LocalMachine       RemoteSigned

PS C:> Set-ExecutionPolicy Restricted -Scope Process -Force
PS C:> Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
Set-ExecutionPolicy : Windows PowerShell updated your execution policy
successfully, but the setting is overridden by a policy defined at a more
specific scope.  Due to the override, your shell will retain its current
effective execution policy of Restricted. Type "Get-ExecutionPolicy -List"
to view your execution policy settings. ...
PS C:> Get-ExecutionPolicy -List

        Scope    ExecutionPolicy
        -----    ---------------
MachinePolicy          Undefined
   UserPolicy          Undefined
      Process         Restricted
  CurrentUser       Unrestricted
 LocalMachine       RemoteSigned

PS C:> .test.ps1
.test.ps1 : File C:test.ps1 cannot be loaded because running scripts is
disabled on this system. ...
PS C:> Set-ExecutionPolicy Unestricted -Scope Process -Force
PS C:> Set-ExecutionPolicy Restricted -Scope CurrentUser -Force
Set-ExecutionPolicy : Windows PowerShell updated your execution policy
successfully, but the setting is overridden by a policy defined at a more
specific scope.  Due to the override, your shell will retain its current
effective execution policy of Restricted. Type "Get-ExecutionPolicy -List"
to view your execution policy settings. ...
PS C:> Get-ExecutionPolicy -List

        Scope    ExecutionPolicy
        -----    ---------------
MachinePolicy          Undefined
   UserPolicy          Undefined
      Process       Unrestricted
  CurrentUser         Restricted
 LocalMachine       RemoteSigned

PS C:> .test.ps1
Hello World!

As you can see, both settings were defined despite the error, but the setting in the more specific scope (Process) still takes precedence, either preventing or allowing script execution.

Since the default scope is LocalMachine the error could be caused by a setting in the CurrentUser or Process scope. However, a more common reason is that script execution was configured via a group policy (either local or domain).

A local group policy can be modified by a local administrator via gpedit.msc (Local Group Policy Editor) as described in this answer.

A domain group policy cannot be superseded by local settings/policies and must be changed by a domain admin via gpmc.msc (Group Policy Management) on a domain controller.

For both local and domain policies the setting can be defined as a computer setting:

Computer Configuration
`-Administrative Templates
  `-Windows Components
    `-Windows PowerShell -> Turn on Script Execution

or as a user setting:

User Configuration
`-Administrative Templates
  `-Windows Components
    `-Windows PowerShell -> Turn on Script Execution

The former are applied to computer objects, whereas the latter are applied to user objects. For local polices there is no significant difference between user and computer policies, because user policies are automatically applied to all users on the computer.

A policy can have one of three states (or five states if you count the 3 settings available for the state Enabled separately):

  • Not Configured: policy does not control PowerShell script execution.
  • Enabled: allow PowerShell script execution.
    • Allow only signed scripts: allow execution of signed scripts only (same as Set-ExecutionPolicy AllSigned).
    • Allow local scripts and remote signed scripts: allow execution of all local scripts (signed or not) and of signed scripts from remote locations (same as Set-ExecutionPolicy RemoteSigned).
    • Allow all scripts: allow execution of local and remote scripts regardless of whether they’re signed or not (same as Set-ExecutionPolicy Unrestricted).
  • Disabled: disallow PowerShell script execution (same as Set-ExecutionPolicy Restricted).

Changes made via Set-ExecutionPolicy only become effective when local and domain policies are set to Not Configured (execution policy Undefined in the scopes MachinePolicy and UserPolicy).

While setting my ExecutionPolicy to Unrestricted, I got the following error:
Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of Restricted.

windows powershell the setting is overridden by a policy defined at a more specific scope

I was trying to run the command

Set-ExecutionPolicy -ExecutionPolicy Unrestricted

But that didn’t work out well.

Luckily the error also gave me some hints:
Type “Get-ExecutionPolicy -List” to view your execution policy settings.
When I ran that command, it returned:

Scope ExecutionPolicy
—– —————
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Restricted
LocalMachine Unrestricted

powershell executionpolicy list scope

PowerShell contains multiple scopes. Each scope has its preference. As long as a Scope is set to Undefined, it won’t hinder. But ifa more specific scope is configured, that scope’s execution policy wins.

Fix Windows PowerShell setting is overridden

To fix Windows PowerShell setting is overridden, I had to set the ExecutionPolicy of the CurrentUser to Unrestricted (or Undefined). To do so, run this cmdlet in Powershell:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser

or

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope CurrentUser

powershell set executionpolicy undefined currentuser

Problem solved.
Error Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope didn’t show up anymore.

In your case, another Scope may be set to Restricted. Replace the scope name if needed. For example:

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope Process

A final note about winning policies

The most specific scope wins, but it also overrides the less specific scope.
It’s different from setting NTFS permissions for example. In NTFS, a combination of Deny Access on a user, and Allow Access to a group, will result in a Deny. Because Deny always wins.
In Powershell’s execution policy, a combination of CurrentUser Unrestricted, and LocalMachine Restricted, will result in an Unrestricted policy.
The default setting of ExecutionPolicies is Undefined for all, except for LocalMachine. That should be set to Restricted. Which can then lead to other errors as I described in a previous post
Setting the LocalMachine policy only would be my advice. It is often not needed to define multiple levels.

By default, Windows settings prevent PowerShell scripts from running. From a security perspective, it is important to restrict untrusted and malicious code from running from PowerShell scripts. The Execution Policy determines the settings for running PowerShell scripts. In this article we’ll look at the available settings for running PS scripts on Windows, how to change the Execution Policy and configure PowerShell script execution policies for domain computers using GPO.

Contents:

  • Running PowerShell Scripts Is Disabled on This System
  • How to Allow PowerShell to Run Scripts Using the Execution Policy?
  • Set PowerShell Execution Policy in Active Directory Using GPO
  • How to Bypass the PowerShell Execution Policy on Windows?

Running PowerShell Scripts Is Disabled on This System

When trying to run any PowerShell script (a PS1 file) on clean Windows 10, the following error occurs:

File C:psscript.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

ps1 cannot be loaded because running powershell scripts is disabled on this system

You can get the current settings for PowerShell script Execution Policy in Windows using the following command:

Get-ExecutionPolicy

Get-ExecutionPolicy

The following PowerShell Execution Policy values are available:

  • Restricted – running PowerShell scripts is disabled, you can execute only interactive commands in the PS console;
  • AllSigned – only signed PS scripts with a digital signature by a trusted publisher are allowed (you can sign a script using a self-signed certificate and add it to trusted root certificates). When running untrusted scripts, the following warning appears:
    Do you want to run software from this untrusted publisher? File .ps1 is published by CN=test1 and is not trusted on your system. Only run scripts from trusted publishers.
  • RemoteSigned – you can run local PowerShell scripts without any restrictions. You can run remote PS files with a digital signature (you cannot run PS1 files downloaded from the Internet or launched from a shared network folder via the UNC path);
  • Unrestricted – all PowerShell scripts are allowed to run;

    When trying to run third-party PowerShell scripts, you may be prompted to confirm launch (see below).

  • Bypass – running any PS files is allowed (no warnings are displayed). The policy is usually used to run PS scripts automatically without displaying any notifications (for example, when scripts are run via GPO, SCCM, Task Scheduler, etc.) and is not recommended for permanent use;
  • Default – resets PowerShell script execution settings to the default ones;

    On Windows 10 the default value for PowerShell Execution Policy is Restricted, and on Windows Server 2016 it is RemoteSigned.

  • Undefined – the policy is not set. The Restricted policy is applied to desktop OSs and RemoteSigned for server ones.

How to Allow PowerShell to Run Scripts Using the Execution Policy?

To change the current value of PowerShell script Execution Policy, the Set-ExecutionPolicy cmdlet is used.

For example, let’s allow to run local PS script files:

Set-ExecutionPolicy RemoteSigned

Confirm changing the Execution Policy for PS1 scripts by pressing Y or A.

Set-ExecutionPolicy RemoteSigned

To avoid showing the confirmation prompt, you may use the Force parameter.

Set-ExecutionPolicy RemoteSigned –Force

If you have set the value of the PowerShell Execution Policy to Unrestricted, you will still see the prompt when trying to run remote scripts from shared folders by the UNC paths or files downloaded from the Internet:

Security warning
Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the
Unblock-File cmdlet to allow the script to run without this warning message.
Do you want to run?
[D] Do not run [R] Run once [S] Suspend [?] Help (default is "D")

powershell security warning Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning message

How PowerShell differentiates between local and remote scripts? It is due to the ZoneId identifier a browser sets in the alternative stream when downloading a file (see the article How does Windows know if a file was downloaded from the Internet?). You can unblock the file by checking Unblock in the file properties or clear the zone label using the Unblock-File cmdlet.

You must also distinguish between different scopes of PowerShell Execution Policy:

  • MachinePolicy – is set using GPO and applies to all users of a computer;
  • UserPolicy – also set using GPO and applies to computer users;
  • Process — Execution Policy settings are applied to the current PowerShell session only (and reset after the powershell.exe process is terminated);
  • CurrentUser – the Execution Policy is applied to the current user only (a parameter of the HKEY_CURRENT_USER registry key);
  • LocalMachine is a policy for all users of a computer (a parameter from the HKEY_LOCAL_MACHINE registry key).

You can set the policy scope using the Scope parameter of the Set-ExecutionPolicy cmdlet. For example:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass –Force

Let’s check the current ExecutionPolicy settings for all scopes:

Get-ExecutionPolicy -List

Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Bypass
CurrentUser Undefined
LocalMachine RemoteSigned

check the current ExecutionPolicy settings for all scopes

The Execution Policy values you set using the Set-ExecutionPolicy cmdlet for CurrentUser and LocalMachine scopes are stored in the registry. For example, run this command:

Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Restricted –Force

Open the HKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell registry key and check the REG_SZ value of the ExecutionPolicy parameter. It should change to Restricted (the allowed parameter values are Restricted, AllSigned, RemoteSigned, Bypass, Unrestricted and Undefined).

check the value of the powershell ExecutionPolicy in registry

The same settings for the CurrentUser scope are located under HKEY_CURRENT_USERSOFTWAREMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell.

Note that the ExecutionPolicy with the AllSigned value on the LocalMachine level is used in a corporate environment the most often. It provides the best balance between security and convenience. For personal use, you can use the RemoteSigned setting on your computer. The Bypass policy may be used only to run some tasks (for example, to run scripts using GPO or tasks in the Task Scheduler).

Set PowerShell Execution Policy in Active Directory Using GPO

You can configure the Execution Policy for PowerShell scripts on servers or domain computers in Active Directory domain using Group Policies.

  1. In the domain GPO editor (gpmc.msc), create a new GPO or edit an existing one and link it to the OU containing computers you want to apply the PowerShell script Execution Policy to;
  2. Open Computer Configuration -> Policies -> Administrative Templates -> Windows Components -> Windows PowerShell in the GPO editor and find the Turn on Script Execution parameter.

    There is the same policy in the user GPO section — User Configuration, but the computer policy has a higher priority.

  3. The policy may have three values:
    1. Allow only signed scripts – corresponding to the AllSigned policy
    2. Allow local scripts and remote signed scripts – corresponding to the PS RemoteSigned policy
    3. Allow all scripts – corresponding to the Unrestricted policy
      Turn on Script Execution using GPO
  4. Set the policy value you want, save the GPO and update Group Policy settings on your computer;
  5. Make sure that new execution settings have been applied to the MachinePolicy scope.
    check powershell execution policy after group policy update

After configuring the Execution Policy using GPO, you won’t be able to change script execution policy settings manually. If you try to change the Execution Policy settings on a computer the GPO is applied to, the following error appears:

Set-ExecutionPolicy: Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings.

Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope

In the same way, you can configure the Execution Policy on a standalone computer using the local GPO editor — gpedit.msc.

How to Bypass the PowerShell Execution Policy on Windows?

There are some tricks that can help you if you want to run a PowerShell script on your computer without changing the Execution Policy settings. For example, I want to run a simple PS1 script that checks if it is run as an administrator.

You can get the script contents using Get-Content and redirect it to the standard input stream of the PS console.

Get-Content c:pscheck_process_elevation.ps1 | PowerShell.exe -noprofile –

Or you can run a new powershell.exe process with the Bypass policy:

powershell.exe -noprofile -executionpolicy bypass -file c:pscheck_process_elevation.ps1

2 Ways to Bypass the PowerShell Execution Policy

Skip to content

При попытке установить любой пакет через NuGet в Visual Studio 2013 (VS 2013) получаю сообщение об ошибке:

Install failed. Rolling back…
Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.

При попытке вызвать консоль в VS 2013 — View — Other Windows — Package Manager Console так же получаю сообщение об ошибке:

Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope.  Due to the override, your shell will retain its current effective execution policy of Unrestricted. Type «Get-ExecutionPolicy -List» to view your execution policy settings. For more information please see «Get-Help Set-ExecutionPolicy».

В групповой политике (gpedit.msc) выставлены настройки

image

image

SNAGHTML12f871

И всё равно, при попытке в Power Shell Console выставить нужные политики, с помощью Set-ExecutionPolicy AllSigned — получаю сообщение об ошибке:

Set-ExecutionPolicy : Оболочка Windows PowerShell успешно обновила вашу политику выполнения, но данный параметр переопределяется политикой, определенной в более конкретной области. В связи с переопределением оболочка сохранит текущую политику выполнения «Unrestricted». Для просмотра параметров политики выполнения введите «Get-ExecutionPolicy -List». Для получения дополнительных сведений введите «Get-Help Set-ExecutionPolicy».
строка:1 знак:1
+ Set-ExecutionPolicy AllSigned
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
+ FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

SNAGHTML185956

РЕШЕНИЕ: Мне помогло, установка параметра реестра ExecutionPolicy = Bypass в разделе HKEY_LOCAL_MACHINESOFTWAREPoliciesMicrosoftWindowsPowerShell

на всякий случай установил такое же значение еще и здесь

HKEY_CURRENT_USERSoftwarePoliciesMicrosoftWindowsPowerShell

После этого консоль в Visual Studio и NuGet заработали.

А политики стали такими:

image

  • Remove From My Forums
  • Question

  • Hello, 

    I have Win 2012 R2, execution policy is set to remotesigned. However when I right-click a script and select run with Powershell it asks for execution policy change. The script is not downloaded from the internet and inside there is nothing about execution
    policy update. 

    Anyway, If I press no or yes, the script executes.

    What this might be?

    thx


    ——————— Leos

Answers

  • Hello Albert,

    well the solution is to update the registry key

    HKEY_CLASSES_ROOTMicrosoft.PowerShellScript.1ShellCommand

    «C:WindowsSystem32WindowsPowerShellv1.0powershell.exe»
    «-Command» «if((Get-ExecutionPolicy ) -ne ‘AllSigned’) { Set-ExecutionPolicy -Scope Process Bypass }; & ‘%1′»

    Either change AllSigned to RemoteSigned or to remove this «Command» completely. Honestly I dont know what the default settings is to try to
    bypass system Execution policy when right-clicking a script.

    «C:WindowsSystem32WindowsPowerShellv1.0powershell.exe» ; & ‘%1′»

    This also works fine and it respects the system Execution policy.

    Leos


    ——————— Leos

    • Marked as answer by

      Tuesday, November 7, 2017 3:05 PM

The other day, I was trying to update my Domain Joined machine with Visual Studio 2017, however, one of the GPO on the Domain blocked VS from updating.

You also, get this error message when trying to use Visual Studio 2017 and Docker to debug applications.

After trying to change the PowerShell Execution Policy and continue with the update, I received the error below.

Error Message

set-executionpolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the
override, your shell will retain its current effective execution policy of AllSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more
information please see "Get-Help Set-ExecutionPolicy".
At line:1 char:1
Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope.

Because it was Sunday and I couldn’t connect to the network and exclude my Laptop from the policy, I had to make a change to the registry and bypass the Domain GPO.

REGEDIT Change

To change the PowerShell execution Policy using, Open Regedit and want to path below.

ComputerHKEY_LOCAL_MACHINESOFTWAREPoliciesMicrosoftWindowsPowerShell

From the Powershell folder, I doubled clicked on ExecutionPolicy and changed the value to unrestricted

After the change, when I run Get-ExecutionPolicy I see the change an I can run the update.

Notes

Remember that this change will work only If you’re not connected to the Domain and have admins rights to the computer.

Once the computer Is connected to the Domain, GPOs will apply to the computer and change the policy.

Powershell execution policy setting is overridden by a policy defined at a more specific scope

December 31, 2017 01:38AM

While setting up execution policy (Set-ExecutionPolicy) on powershell, there might be a below error.

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope.  Due to the override, your shell will retain its current effective execution policy of Unrestricted. Type «Get-ExecutionPolicy -List» to view your execution policy settings. For more
information please see «Get-Help Set-ExecutionPolicy».
At line:1 char:1
+ Set-ExecutionPolicy Restricted
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
    + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

Microsoft powershell get-executionpolicy, set-executionpolicy, overridden a policy, group policy, list of execution policy, restricted, unrestricted

This error appears due to below 2 reasons.
1) If different execution policy is setup at execution Scope level (Process, CurrentUser or LocalMachine) using cmdlet Set-ExecutionPolicy, as shown in Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled. MachinePolicy and UserPolicy can only be changed and setup using Group policy as shown in 2nd point.
2) Setup Powershell execution policy with Group Policy. 

To resolve this issue, change the manual execution scope of Process, CurrentUser or LocalMachine to undefinedUndefined means there is no execution policy set in the current scope. If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy. Running only Set-ExecutionPolicy without scope syntax changes LocalMachine by default and if tried to modify it, it will always generate error if Group policy is setup.

Current scope list can be viewed using command Get-ExecutionPolicy -List and changing the policy doesn’t show error Set-ExecutionPolicy Undefined  -Scope CurrentUser.

If all scope policies are set to undefined (except LocalMachine), changing configuration will not show any error.

Microsoft powershell, get-executionpolicy -list, set-executionpolicy undefined currentuser, machine policy userpolicy, process, localmachine

Useful Articles
Powershell Trick : Execute or run any file as a script file
Installing, importing and using any module in powershell
How to Install and Use Microsoft PowerShell on Linux

Go Back

Like this post? Please share to your friends:
  • Session save path c windows temp
  • Session drummer 3 vst скачать бесплатно для windows
  • Servicing что это за папка windows 10 можно ли удалять
  • Servicing stack windows 10 1809 x64 скачать
  • Servicing stack update for windows 10 удалить