powershellbatch-file

Unable to Run PowerShell Script from Batch File: Common Errors and Fixes


I wrote a PowerShell script to give run access to run without admin privilege. So I need to run that script from batch file. Here I attached my PowerShell script and my batch file. I am not able to run the PowerShell script from my batch file.

# Attempting to allow script execution
powershell -File "%~dpn0.ps1" %*

# Setting Execution Policy to Unrestricted
Start-Process PowerShell -ArgumentList "Set-ExecutionPolicy Unrestricted -Force" -Verb RunAs

# Setting registry permissions
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(
    "SOFTWARE\Wow6432Node\Unicorn",
    [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
    [System.Security.AccessControl.RegistryRights]::ChangePermissions
)
$acl = $key.GetAccessControl()
$rule = New-Object System.Security.AccessControl.RegistryAccessRule (
    ".\USERS", "FullControl", @("ObjectInherit", "ContainerInherit"), "None", "Allow"
)
$acl.SetAccessRule($rule)
$key.SetAccessControl($acl)

Write-Host "Successfully set permission to PM Registry!"

@ECHO OFF
PowerShell.exe -Command "& '%~dpn0.ps1'"
PAUSE

Problem is: When I run the batch file, I encounter an error indicating that script execution is not allowed on my system. Here’s the error message:

enter image description here


Solution

  • On your system, the execution of PowerShell scripts is not allowed. Either allow it, by executing (with administrative privileges):

    Set-ExecutionPolicy RemoteSigned
    

    Or bypass it (in your .bat):

    PowerShell.exe -ExecutionPolicy Bypass -File .\Access.ps1
    

    Inside Access.ps1, the following line is pretty much useless:

    Start-Process PowerShell -ArgumentList "Set-ExecutionPolicy Unrestricted -Force" -Verb RunAs
    

    as you already need permissions to execute scripts to run this script.