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

使用New-Item与subprocess以管理员权限创建符号链接

问题与解决方案

原可运行的PowerShell命令

用于创建符号链接的原始PowerShell命令如下:

New-Item -ItemType SymbolicLink -Path "C:\Users\user1\Saved Games\Scripts\BIOS" -Target "C:\Users\user1\Saved Games\bios\Scripts\BIOS"

最初的Python实现思路

为了通过Python的subprocess模块以管理员权限运行该命令,最初的写法如下:

def run_cmd(*args):
    p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, error = p.communicate()
    return out, error

cmd_symlink = '"New-Item -ItemType SymbolicLink -Path "C:\Users\user1\Saved Games\Scripts\BIOS" -Target "C:\Users\user1\Saved Games\bios\Scripts\BIOS"'
ps_command = f"& {{Start-Process powershell.exe -argumentlist '-command {cmd_symlink}' -Verb RunAs}}"
command = ['powershell.exe', '-command', ps_command]
run_cmd(command)

最初写法不可行的原因

  1. 引号与转义错误:cmd_symlink中嵌套的双引号未正确转义,Python会直接解析内层双引号导致语法错误;同时路径中的反斜杠未做转义,会被Python当作转义字符处理。
  2. 冗余进程启动:通过powershell.exe再次启动powershell.exe属于多余操作,徒增复杂度。
  3. 不必要的语法包裹:& { ... }的包裹完全没必要,反而加剧了引号处理的难度。

最终解决方案代码

修正后的Python代码解决了转义、冗余等问题,可正常运行:

def run_cmd(*args):
    p = subprocess.Popen(*args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, error = p.communicate()
    return out, error

cmd_symlink = r'"New-Item -ItemType SymbolicLink -Path \"C:\Users\user1\Saved Games\Scripts\BIOS\" -Target \"C:\Users\user1\Saved Games\bios\Scripts\BIOS\""'
ps_command = f"Start-Process pwsh.exe -argumentlist '-command {cmd_symlink}' -Verb RunAs"
command = ['pwsh.exe', '-command', ps_command]
run_cmd(command)

关键修改点

  • 使用Python原始字符串r''定义命令,避免反斜杠被当作转义字符解析。
  • 用\"转义路径中的双引号,确保PowerShell能正确识别带空格的路径参数。
  • 改用pwsh.exe(PowerShell Core),若需兼容Windows PowerShell可替换为powershell.exe。
  • 移除了不必要的& { ... }语法包裹,简化命令结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:34:57