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

如何从其他文件夹运行带参数的PowerShell脚本?

问题描述

我有一个接收两个参数的PowerShell脚本,参数定义如下:

param([string]$folder, [string]$filename)

在脚本所在文件夹内运行时,脚本可正常执行:

C:\scriptfolder> ".\script.ps1" "C:\folder for argument" "filename.ext"

但从其他文件夹运行该脚本时出现错误:

C:\otherfolder> "C:\scriptfolder\script.ps1" "C:\folder for argument" "filename.ext"

错误提示:

At line:1 char:nn
Unexpected token '"C:\folder for argument"' in expression or statement.

请问如何从其他文件夹运行该脚本?

解决方法
  • 使用调用操作符&执行脚本:
    PowerShell里直接写带引号的脚本路径加参数,会被当成字符串处理而非执行脚本。用&能明确告诉PowerShell要执行指定路径的脚本,参数也能正确传递:

    C:\otherfolder> & "C:\scriptfolder\script.ps1" "C:\folder for argument" "filename.ext"
    
  • 无空格路径的简化写法:
    如果脚本所在路径没有空格,也可以直接去掉引号执行:

    C:\otherfolder> C:\scriptfolder\script.ps1 "C:\folder for argument" "filename.ext"
    

    但路径包含空格时必须用&加引号的方式,避免出错。

  • 永久便捷运行方案:
    把脚本所在文件夹添加到PowerShell的Path环境变量里,之后不管在哪个文件夹都能直接用脚本名运行:
    临时生效(仅当前PowerShell会话):

    $env:Path += ";C:\scriptfolder"
    

    之后直接运行:

    C:\otherfolder> script.ps1 "C:\folder for argument" "filename.ext"
    

    要是想永久生效,去系统环境变量设置界面,把C:\scriptfolder添加到Path变量里就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:15:57