如何从其他文件夹运行带参数的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
相关产品推荐
相关产品推荐

