You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

以其他用户身份高权限运行进程时遇目录无效错误的排查

问题:跨用户高权限执行EXE时出现「目录名无效」错误

我编写了一个PowerShell脚本,用于接收用户凭据后,以该用户身份高权限执行EXE文件,脚本内容如下:

# Function to run an executable with elevated privileges on a different user
function Run-ElevatedExeOnUser {
    
    $credentials = Get-Credential

    $command = {
        Start-Process -FilePath '"C:\Windows\notepad.exe"' -Verb RunAs
    }

    # Start a new PowerShell process with the credentials and command
    Start-Process powershell.exe -Credential $credentials -ArgumentList "-NoProfile", "-Command", $command

}

Run-ElevatedExeOnUser

该脚本在开发环境可正常运行,但在另一环境中出现如下错误:

Start-Process : This command cannot be run due to the error: The directory name is invalid.
At C:\test\testscript.ps1:17 char:5
+     Start-Process powershell.exe -Credential $credentials -ArgumentLi ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

已确认该用户属于管理员组,且通过Shift+右键选择「以其他用户身份运行」可正常启动该EXE。请问可能的原因是什么?遗漏了哪些配置?


可能的原因与解决方法

1. 目标用户的默认工作目录不存在

使用-Credential启动进程时,PowerShell默认会将目标用户的家目录(如C:\Users\目标用户名)作为工作目录。如果该用户从未登录过系统,或者家目录被删除/移动,就会触发「目录名无效」的错误。

解决方法:在Start-Process中显式指定-WorkingDirectory参数,使用一个存在的公共目录:

Start-Process powershell.exe -Credential $credentials -WorkingDirectory "C:\Windows" -ArgumentList "-NoProfile", "-Command", $command

2. 脚本中的引号转义错误

原脚本中$command块里的"是HTML转义字符,实际运行时会被解析为无效的引号格式,导致Start-Process无法正确识别文件路径。

解决方法:使用PowerShell原生的引号写法,去掉多余转义(路径无空格时无需额外加引号):

$command = {
    Start-Process -FilePath 'C:\Windows\notepad.exe' -Verb RunAs
}

3. 嵌套提权的权限上下文冲突

用-Credential启动的PowerShell进程已经是目标用户身份,再使用-Verb RunAs尝试提权,可能在部分环境下触发UAC异常限制(比如目标用户UAC级别过高,或未启用内置管理员的UAC过滤)。

解决方法:

  • 检查目标用户UAC设置:确保UAC级别未设为「始终通知」,或通过组策略启用内置管理员的UAC批准模式(路径:计算机配置>Windows设置>安全设置>本地策略>安全选项>用户账户控制: 内置管理员账户的管理员批准模式设为「已启用」)。
  • 调整脚本逻辑:若目标用户本身是管理员,可直接运行程序无需嵌套提权;注意-Credential和-Verb RunAs不能同时使用,需根据场景二选一。

内容的提问来源于stack exchange,提问作者Kaveesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:41:22