Set executionpolicy оболочка windows powershell успешно обновила вашу политику выполнения

Set executionpolicy оболочка windows powershell успешно обновила вашу политику выполнения

При попытке установить любой пакет через 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) выставлены настройки

И всё равно, при попытке в 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

РЕШЕНИЕ : Мне помогло, установка параметра реестра ExecutionPolicy = Bypass в разделе HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell

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

HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\PowerShell

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

Настройка политики запуска скриптов (Execution Policy) PowerShell

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

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

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

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

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

  • Restricted – запрещен запуск скриптов PowerShell, можно выполнять только интерактивные команды в консоли;
  • AllSigned – разрешено выполнять только подписанные PS скрипты с цифровой подписью от доверенного издателя (можно подписать скрипт самоподписанным сертификатом и добавить его в доверенные). При запуске недоверенных скриптов появляется предупреждение:

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

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

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

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

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

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

    Set-ExecutionPolicy RemoteSigned –Force

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

    Также следует различать различные области действия политик выполнения скриптов 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 для всех областей:

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

    Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Restricted –Force

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

    Аналогичные настройки для области CurrentUser находятся в разделе реестра пользователя HKEY_CURRENT_USER\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.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 вы не сможете изменить настройки политики выполнения скриптов вручную. При попытке изменить настройки Execution Policy на компьютере, на который применяется такая GPO, появится ошибка:

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

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

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

    Set-Execution Policy

    Sets the PowerShell execution policies for Windows computers.

    Syntax

    Description

    The Set-ExecutionPolicy cmdlet changes PowerShell execution policies for Windows computers. For more information, see about_Execution_Policies.

    Beginning in PowerShell 6.0 for non-Windows computers, the default execution policy is Unrestricted and can’t be changed. The Set-ExecutionPolicy cmdlet is available, but PowerShell displays a console message that it’s not supported.

    An execution policy is part of the PowerShell security strategy. Execution policies determine whether you can load configuration files, such as your PowerShell profile, or run scripts. And, whether scripts must be digitally signed before they are run.

    The Set-ExecutionPolicy cmdlet’s default scope is LocalMachine, which affects everyone who uses the computer. To change the execution policy for LocalMachine, start PowerShell with Run as Administrator.

    To display the execution policies for each scope in the order of precedence, use Get-ExecutionPolicy -List . To see the effective execution policy for your PowerShell session use Get-ExecutionPolicy with no parameters.

    Examples

    Example 1: Set an execution policy

    This example shows how to set the execution policy for the local computer.

    The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the RemoteSigned policy. The Scope parameter specifies the default scope value, LocalMachine. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.

    Example 2: Set an execution policy that conflicts with a Group Policy

    This command attempts to set the LocalMachine scope’s execution policy to Restricted. LocalMachine is more restrictive, but isn’t the effective policy because it conflicts with a Group Policy. The Restricted policy is written to the registry hive HKEY_LOCAL_MACHINE.

    The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the Restricted policy. The Scope parameter specifies the default scope value, LocalMachine. The Get-ChildItem cmdlet uses the Path parameter with the HKLM provider to specify registry location.

    Example 3: Apply the execution policy from a remote computer to a local computer

    This command gets the execution policy object from a remote computer and sets the policy on the local computer. Get-ExecutionPolicy sends a Microsoft.PowerShell.ExecutionPolicy object down the pipeline. Set-ExecutionPolicy accepts pipeline input and doesn’t require the ExecutionPolicy parameter.

    The Invoke-Command cmdlet is executed at the local computer and sends the ScriptBlock to the remote computer. The ComputerName parameter specifies the remote computer, Server01. The ScriptBlock parameter runs Get-ExecutionPolicy on the remote computer. The Get-ExecutionPolicy object is sent down the pipeline to the Set-ExecutionPolicy . Set-ExecutionPolicy applies the execution policy to the local computer’s default scope, LocalMachine.

    Example 4: Set the scope for an execution policy

    This example shows how to set an execution policy for a specified scope, CurrentUser. The CurrentUser scope only affects the user who sets this scope.

    Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the AllSigned policy. The Scope parameter specifies the CurrentUser. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.

    The effective execution policy for the user becomes AllSigned.

    Example 5: Remove the execution policy for the current user

    This example shows how use the Undefined execution policy to remove an execution policy for a specified scope.

    Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the Undefined policy. The Scope parameter specifies the CurrentUser. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.

    Example 6: Set the execution policy for the current PowerShell session

    The Process scope only affects the current PowerShell session. The execution policy is saved in the environment variable $env:PSExecutionPolicyPreference and is deleted when the session is closed.

    The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the AllSigned policy. The Scope parameter specifies the value Process. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.

    Example 7: Unblock a script to run it without changing the execution policy

    This example shows how the RemoteSigned execution policy prevents you from running unsigned scripts.

    A best practice is to read the script’s code and verify it’s safe before using the Unblock-File cmdlet. The Unblock-File cmdlet unblocks scripts so they can run, but doesn’t change the execution policy.

    The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the RemoteSigned policy. The policy is set for the default scope, LocalMachine.

    The Get-ExecutionPolicy cmdlet shows that RemoteSigned is the effective execution policy for the current PowerShell session.

    The Start-ActivityTracker.ps1 script is executed from the current directory. The script is blocked by RemoteSigned because the script isn’t digitally signed.

    For this example, the script’s code was reviewed and verified as safe to run. The Unblock-File cmdlet uses the Path parameter to unblock the script.

    To verify that Unblock-File didn’t change the execution policy, Get-ExecutionPolicy displays the effective execution policy, RemoteSigned.

    The script, Start-ActivityTracker.ps1 is executed from the current directory. The script begins to run because it was unblocked by the Unblock-File cmdlet.

    Parameters

    Prompts you for confirmation before running the cmdlet.

    Type: SwitchParameter
    Aliases: cf
    Position: Named
    Default value: False
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies the execution policy. If there are no Group Policies and each scope’s execution policy is set to Undefined, then Restricted becomes the effective policy for all users.

    The acceptable execution policy values are as follows:

    • AllSigned. Requires that all scripts and configuration files are signed by a trusted publisher, including scripts written on the local computer.
    • Bypass. Nothing is blocked and there are no warnings or prompts.
    • Default. Sets the default execution policy. Restricted for Windows clients or RemoteSigned for Windows servers.
    • RemoteSigned. Requires that all scripts and configuration files downloaded from the Internet are signed by a trusted publisher. The default execution policy for Windows server computers.
    • Restricted. Doesn’t load configuration files or run scripts. The default execution policy Windows client computers.
    • Undefined. No execution policy is set for the scope. Removes an assigned execution policy from a scope that is not set by a Group Policy. If the execution policy in all scopes is Undefined, the effective execution policy is Restricted.
    • Unrestricted. Beginning in PowerShell 6.0, this is the default execution policy for non-Windows computers and can’t be changed. Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the internet, you’re prompted for permission before it runs.
    Type: ExecutionPolicy
    Accepted values: AllSigned, Bypass, Default, RemoteSigned, Restricted, Undefined, Unrestricted
    Position: 0
    Default value: None
    Accept pipeline input: True
    Accept wildcard characters: False

    Suppresses all the confirmation prompts. Use caution with this parameter to avoid unexpected results.

    Type: SwitchParameter
    Position: Named
    Default value: False
    Accept pipeline input: False
    Accept wildcard characters: False

    Specifies the scope that is affected by an execution policy. The default scope is LocalMachine.

    The effective execution policy is determined by the order of precedence as follows:

    • MachinePolicy. Set by a Group Policy for all users of the computer.
    • UserPolicy. Set by a Group Policy for the current user of the computer.
    • Process. Affects only the current PowerShell session.
    • CurrentUser. Affects only the current user.
    • LocalMachine. Default scope that affects all users of the computer.

    The Process scope only affects the current PowerShell session. The execution policy is saved in the environment variable $env:PSExecutionPolicyPreference , rather than the registry. When the PowerShell session is closed, the variable and value are deleted.

    Execution policies for the CurrentUser scope are written to the registry hive HKEY_LOCAL_USER.

    Execution policies for the LocalMachine scope are written to the registry hive HKEY_LOCAL_MACHINE.

    Type: ExecutionPolicyScope
    Accepted values: CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy
    Position: 1
    Default value: LocalMachine
    Accept pipeline input: True
    Accept wildcard characters: False

    Shows what would happen if the cmdlet runs. The cmdlet is not run.

    Type: SwitchParameter
    Aliases: wi
    Position: Named
    Default value: False
    Accept pipeline input: False
    Accept wildcard characters: False

    Inputs

    Microsoft.PowerShell.ExecutionPolicy, System.String

    You can pipe an execution policy object or a string that contains the name of an execution policy to Set-ExecutionPolicy .

    Outputs

    None

    Set-ExecutionPolicy doesn’t return any output.

    Notes

    Set-ExecutionPolicy doesn’t change the MachinePolicy and UserPolicy scopes because they are set by Group Policies.

    Set-ExecutionPolicy doesn’t override a Group Policy, even if the user preference is more restrictive than the policy.

    If the Group Policy Turn on Script Execution is enabled for the computer or user, the user preference is saved, but it is not effective. PowerShell displays a message that explains the conflict.

    Читайте также:  Sennheiser momentum m3aebtxl windows
Оцените статью