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

PowerShell脚本接收含空格完整路径参数的问题求助

问题:PowerShell脚本接收含空格路径参数时被截断

我正在编写PowerShell脚本extract_data.ps1,该脚本接收两个参数:XML文件路径和XSL文件路径。调用方式为:

extract_data.ps1 "C:/Temp/YBA_B Running hyp 2\data.xml" "C:/Temp/YBA_B Running hyp 2\data.xsl"

脚本内容如下:

#Parameters
Param(
    #[Parameter(Mandatory=$True)]
    [string]$xml,

    #[Parameter(Mandatory=$True)]
    [string]$xsl
)

Write-Host xmlfilelocation: $xml
Write-Host xslfilelocation: $xsl

当路径中包含空格时,路径会被截断。例如传入上述路径时,输出结果为:

xmlfilelocation: C:/Temp/YBA_B
xslfilelocation: Running

而非预期的完整路径。请问有解决办法吗?


解决方案

1. PowerShell环境内正确调用脚本

在PowerShell会话中执行脚本时,只需将每个带空格的路径参数用英文双引号完整包裹,PowerShell会自动识别引号内的内容为单个参数,不会因空格拆分。

2. 命令提示符(cmd)中调用脚本的正确方式

若在cmd环境下运行PowerShell脚本,必须通过powershell.exe启动并指定-File参数,同时将脚本路径和所有参数用英文双引号包裹:

powershell.exe -File "C:\你的脚本路径\extract_data.ps1" "C:/Temp/YBA_B Running hyp 2\data.xml" "C:/Temp/YBA_B Running hyp 2\data.xsl"

直接在cmd中运行.ps1脚本会让cmd自行拆分参数,导致空格截断问题。

3. 完善脚本参数定义(可选)

取消注释[Parameter(Mandatory=$True)],强制要求传入参数避免遗漏;同时输出时用引号包裹变量,更清晰查看完整路径:

#Parameters
Param(
    [Parameter(Mandatory=$True)]
    [string]$xml,

    [Parameter(Mandatory=$True)]
    [string]$xsl
)

Write-Host "xmlfilelocation: '$xml'"
Write-Host "xslfilelocation: '$xsl'"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:01:15