首页 > 解决方案 > 无法使用批处理文件运行 PowerShell 脚本

问题描述

我编写了一个 PowerShell 脚本来授予运行权限以在没有管理员权限的情况下运行。所以我需要从批处理文件中运行该脚本。在这里,我附上了我的 PowerShell 脚本和批处理文件。我无法从我的批处理文件运行 PowerShell 脚本。

访问.ps1

powershell -File "%~dpn0.ps1" %*
Start-Process PowerShell -ArgumentList "Set-ExecutionPolicy Unrestricted -Force" -Verb RunAs
$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!"

访问.bat

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

这是错误

在此处输入图像描述

标签: powershellbatch-file

解决方案


在您的系统上,不允许执行 PowerShell 脚本。通过执行(具有管理权限)允许它:

Set-ExecutionPolicy RemoteSigned

或绕过它(在你的.bat):

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

在里面Access.ps1,下面这行几乎没用:

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

因为您已经需要执行脚本的权限才能运行此脚本。


推荐阅读