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
相关产品推荐
相关产品推荐

