如何在批处理调用的PowerShell脚本中添加-OutputPath参数
批处理调用PowerShell脚本传递
-OutputPath参数失败排查 问题背景
原本通过批处理调用PowerShell脚本可正常在本地保存输出,现在需要添加-OutputPath Z:\Current参数指定输出路径(支持本地/UNC路径),但多次尝试插入位置后,脚本仍使用默认路径,无报错。
原正常工作的批处理代码
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""%~dpn0.ps1 -Update""' -Verb RunAs}"
尝试添加参数后的无效批处理代码
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""%~dpn0.ps1 -OutputPath Z:\Current""' -Verb RunAs}"
PowerShell脚本中输出路径的判断逻辑
# If -OutputPath not specified, set default If (-not($OutputPath)) { Switch ($OSPlatform) { "Windows" { $OutputPath = "$env:PUBLIC\Documents\ Compliance" if (!(Test-Path $OutputPath)) { $null = New-Item -Path $(Split-Path -Path $OutputPath -Parent) -Name $(Split-Path -Path $OutputPath -Leaf) -ItemType Directory } } "Linux" { $OutputPath = "/opt/STIG_Compliance" if (!(Test-Path $OutputPath)) { sudo mkdir $OutputPath } } } }
问题原因
当前写法错误地将脚本路径和参数放在同一个双引号包裹的字符串中,PowerShell解析-File参数时,会把"%~dpn0.ps1 -OutputPath Z:\Current"当作单个脚本文件路径而非脚本路径加参数。因该路径不存在,脚本未接收到-OutputPath参数,最终触发默认路径逻辑。
正确写法
需将脚本路径单独用双引号包裹,参数放在引号外部,同时处理批处理中的转义规则:
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File ""%~dpn0.ps1"" -Update -OutputPath ""Z:\Current""' -Verb RunAs}"
关键调整点
- 脚本路径
%~dpn0.ps1单独用""包裹,确保PowerShell正确识别为脚本文件路径 -Update和-OutputPath Z:\Current作为独立参数,放在脚本路径引号外部- 若输出路径包含空格或特殊字符,需给路径也添加
""包裹(如""Z:\My Output Folder"")
可选优化:脚本参数声明
为确保参数被正确接收,建议在PowerShell脚本开头明确声明参数:
param( [switch]$Update, [string]$OutputPath ) # 原输出路径判断逻辑...
内容的提问来源于stack exchange,提问作者regrahc
相关产品推荐
相关产品推荐

