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

双击JSON启动PS2EXE编译的PowerShell脚本时如何获取触发文件路径

解决方案

核心原因

你观测到$PWD始终指向System32是正常现象:Windows通过「打开方式」启动关联程序时,默认会将System32设为程序的工作目录,被双击的JSON文件路径不会通过工作目录传递,而是作为第一个命令行参数传入你的编译后程序。

实现方法

修改你的原始PowerShell脚本,增加命令行参数判断逻辑,优先读取传入的JSON路径,参数不存在时再走原有文件选择逻辑即可,参考代码如下:

$targetJson = $args[0]
$finalLoadPath = $null

# 判断是否传入了有效JSON文件路径
if ($targetJson -and (Test-Path -Path $targetJson -PathType Leaf) -and $targetJson.EndsWith('.json', [System.StringComparison]::OrdinalIgnoreCase)) {
    $finalLoadPath = $targetJson
}
else {
    # 此处粘贴你原有弹出文件选择框的逻辑
    Add-Type -AssemblyName System.Windows.Forms
    $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $openFileDialog.Filter = "JSON配置文件|*.json"
    $dialogResult = $openFileDialog.ShowDialog()
    
    if ($dialogResult -eq [System.Windows.Forms.DialogResult]::OK) {
        $finalLoadPath = $openFileDialog.FileName
    }
    else {
        # 用户取消选择时可直接退出程序
        exit
    }
}

# 后续你原有加载、编辑JSON的逻辑直接使用$finalLoadPath即可

验证与注意事项

  • 修改完脚本后重新用PS2EXE编译,替换原有exe文件即可生效
  • 若修改后仍收不到文件路径,可检查注册表关联规则:定位到HKEY_CLASSES_ROOT\Applications\你的exe文件名\shell\open\command,确保默认值为"exe完整路径" "%1",末尾的"%1"是系统传递文件路径的占位符,缺失的话手动补上即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:15:04