Problem
You’re trying to run a PowerShell script (let’s call it MyScript.ps1
) in Windows 11, and you encounter an error similar to the following:
At line:1 char:1 + .\MyScript.ps1 + ~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess
This error is caused by PowerShell’s script execution policies, which restrict the running of PowerShell scripts as a security measure.
Solution
Step 1: Check the Current Execution Policy
- Open PowerShell as an Administrator.
- Search for “PowerShell” in the Start Menu, right-click on it, and choose “Run as administrator”.
- Check Execution Policy.
- Enter the command
Get-ExecutionPolicy
and hit Enter. - Take note of the current policy setting. If it’s set to
Restricted
, scripts will not be allowed to run.
Step 2: Change the Execution Policy
- Choose a Policy Setting.
- The execution policy options include
Restricted
,AllSigned
,RemoteSigned
, andUnrestricted
.
- Change the Policy.
- To set it to Unrestricted (less secure but allows any script to run), enter
-
Set-ExecutionPolicy Unrestricted
- To set it to RemoteSigned (recommended for most users), enter
-
Set-ExecutionPolicy RemoteSigned
Step 3: Run the Script Again
- Navigate to the Script Location.
- Use
cd path/to/script
to move to the directory containingMyScript.ps1
.
- Execute the Script.
- Run the script again with
.\MyScript.ps1
.
Step 4: Revert the Policy (Optional)
- Revert to Original Policy.
- If you changed the execution policy to run the script, consider reverting it back to its original setting for security reasons.
- Use
Set-ExecutionPolicy
followed by the original policy you noted in Step 1.
Key Points to Remember
- Make sure you have administrative rights to change the execution policy.
- Always be conscious of security implications when changing these settings.
By following these steps, you should be able to resolve the UnauthorizedAccess
error and successfully run your PowerShell script.