Home > Enterprise >  How do I get my own PowerShell script to run? Keep getting an error
How do I get my own PowerShell script to run? Keep getting an error

Time:09-27

I have tried:

    ##powershell.exe -executionpolicy -bypass
    ##Unblock-File -Path C:\SRM.ps1
    Set-ExecutionPolicy -Scope Process -ExecutionPolicy  ByPass

NO matter what I do I keep getting this error:

File C:\SRM.ps1 cannot be loaded. The file C:\SRM.ps1 is not digitally signed. You cannot run this script on the current system.

Im on the latest windows 11 version. Using Powershell ISE I am running the app as administrator.

What else is there?

CodePudding user response:

Your effective execution policy is AllSigned, meaning that only cryptographically signed script files (*.ps1) are permitted to run, irrespective of whether they're local files or have been downloaded from the web (that is, Unblock-File doesn't make a difference).

As Olaf points out, trying to change the execution policy from inside a script cannot work if the effective execution policy prevents execution of that script to begin with.

Using the the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7 ) with -ExecutionPolicy Bypass is the right approach in principle if the intent is to override the effective execution policy for the given PowerShell session (process) only.

However, overriding the effective execution policy from the command line / via
Set-ExecutionPolicy fundamentally does not work if your execution policy is controlled via GPOs (Group Policy Objects)
.

To determine if your machine's / user account's execution policy is controlled by GPOs, examine the output from Get-ExecutionPolicy -List:
If the values for scopes MachinePolicy or UserPolicy show a value other than Undefined, a GPO policy is in effect; if both values are different from Undefined, the MachinePolicy value takes precedence; the output order in general implies the precedence order.

In other words: Only if Get-ExecutionPolicy's output starts with the following two entries can you override the execution policy using the command line or Set-ExecutionPolicy:

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

Short of modifying the GPOs to change the effective policy, there is no direct workaround, though you can use the CLI with -Command to submit commands that read a script file into memory and execute it there via Invoke-Expression (though this cmdlet should generally be avoided), though this won't work for scripts that rely on reflection features such as $PSCommandPath and $PSScriptRoot to determine their own file and directory path.

  • Related