windows – How do you successfully change execution policy and enable execution of PowerShell scripts – Stack Overflow

Get-executionpolicy

Посмотреть текущие настройки политики во всех областях применения можно выполнив командлет Get-Executionpolicy с параметром list.

Пример:

Результат выполнения командлета:

How do you successfully change execution policy and enable execution of powershell scripts

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         RestrictedCurrentUser       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       UnrestrictedCurrentUser         Restricted
 LocalMachine       RemoteSigned

PS C:> .test.ps1Hello 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).

:/>  Несколько рабочих столов в Windows 10, как это?

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).

:/>  Какие файлы и папки Windows можно удалить для освобождения места на диске

Security risks of set-executionpolicy -executionpolicy remotesigned

PowerShell execution policies are made, more to avoid a wrong script execution by error, than for security purposes.

Remember the Bypass ExecutionPolicy who does not care about execution policies. The only way to block this, is to block it by group policies.

But even with it, user who wants to execute a script can always do it. Try the above code in an environment lab where you have blocked scripts by group policy, then run this code in PowerShell, do not exit PowerShell and try to run any script, it will run :

$context = $ExecutionContext.GetType().GetField('_context', 'NonPublic, Instance').GetValue($ExecutionContext)
$field = $context.GetType().GetField('_authorizationManager', 'NonPublic, Instance')
$field.SetValue($context, (New-Object System.Management.Automation.AuthorizationManager 'Microsoft.PowerShell'))

It is a long time that malwares use PowerShell, whatever are the execution policies.

So as Wasif said, you can use RemoteSigned without any remorse 😉

Set-executionpolicy

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

-ExecutionPolicyУказывает значение политики. Может иметь следующие значения:  Restricted, AllSigned, RemoteSigned, Unrestricted, Bypass, Undefined. Данный параметр обязательный для указания. Если не указан, во время выполнения комадлет попросит указать значения.

Вывод:Укажите значения для следующих параметров: ExecutionPolicy:

Изменение параметров политики запуска скриптов, с помощью групповых политик.

В груповой политике, параметр контролирующая запуск скриптов находиться по пути:

для MachinePolicy:

Изменение параметров политики, при запуске консоли.

Так же можно задать значение области применения Process при запуске консоли PowerShell c помощью параметра executionpolicy. Пример:

Результат выполнения:

Области применения политики.

Областей применений пять:

Разрешить запуск скриптов powershell (powershell execution policy)

windows - How do you successfully change execution policy and enable execution of PowerShell scripts - Stack Overflow

ОПИСАНИЕ

По умолчанию скрипты Powershell блокируются для запуска. Механизм этот называется Execution Policy. Однако, зачастую необходимо разрешить выполнение скриптов, чтобы, например, иметь возможность выполнять их по расписанию в планировщике заданий.

Чтобы узнать, какая сейчас установлено политика, нужно воспользоваться командой

Get-ExecutionPolicy

Значения этой политики хранятся в реестре по следующему пути:

:/>  Самопроизвольное изменение яркости монитора — ноутбук меняет яркость сам! Почему?

КомпьютерHKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell1ShellIds Microsoft.PowerShell

строковый параметр «ExecutionPolicy»

windows - How do you successfully change execution policy and enable execution of PowerShell scripts - Stack Overflow

По умолчанию значение этого параметра выставлено в «Restricted» (ограниченный), что и запрещает выполнение скриптов.

На самом деле, область применения политики различная — она может устанавливаться на разных уровнях системы, таким образом она будет распространяться на компьютер (будет действовать для всех пользователей), только на текущего пользователя и т.п. Посмотреть эту информацию можно, добавив параметр -list

Get-ExecutionPolicy -list
windows - How do you successfully change execution policy and enable execution of PowerShell scripts - Stack Overflow

ИЗМЕНЕНИЕ ПОЛИТИКИ

Чтобы сменить политику, необходимо воспользоваться командой:

Set-ExecutionPolicy

Доступные значения:

Unrestricted, RemoteSigned, AllSigned, Restricted, Default, Bypass, Undefined

Наиболее интересны для нас первые четыре:

Restricted — выполнение сценариев запрещено. Эта опция установлена по умолчанию. Команды в таком случае можно выполнять только в интерактивном режиме.

All Signed — разрешено выполнение только сценариев, подписанных доверенным издателем.

RemoteSigned — разрешено выполнение любых сценариев, созданных локально, а сценарии, созданные на удаленных системах, выполняются только в том случае, если подписаны доверенным издателем.

Unrestricted — разрешено выполнение абсолютно любых сценариев.

Наиболее безопасным будет параметр RemoteSigned, который будет выполнять только сценарии, созданные вами локально.

Чтобы изменить политику, запустите Powershell от имени администратора и введите:

Set-ExecutionPolicy RemoteSigned

Видим запрос

Изменение политики выполнения
Политика выполнения защищает компьютер от ненадежных сценариев. Изменение политики выполнения может поставить под угрозу безопасность системы, как описано в разделе справки, вызываемом командой about_Execution_Policies и расположенном по адресу https:/go.microsoft.com/fwlink/?LinkID=135170 . Вы хотите изменить политику выполнения?
[Y] Да — Y [A] Да для всех — A [N] Нет — N [L] Нет для всех — L [S] Приостановить — S [?] Справка
(значением по умолчанию является «N»):

Выбираем пункт A .

windows - How do you successfully change execution policy and enable execution of PowerShell scripts - Stack Overflow

Оставьте комментарий