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

PowerShell脚本中Dir参数后变量无法解析的问题求助

PowerShell驱动提取脚本中Dir参数变量无法解析的解决方法

我正在用PowerShell实现驱动提取自动化,为MECM构建驱动包时遇到问题:脚本里/DIR参数后的变量始终无法解析为实际路径字符串。尝试了单引号、双引号、转义引号等多种写法都失败了,以下是测试的代码和对应报错:

第一种写法

$Extracted = "C:\Temp2\Extracted" 
$DriverPKGFolder = Read-Host -Prompt "enter the name of the folder the extraction will create"
Get-ChildItem -Path c:\temp2\driverdownloads -Filter *.exe -Depth 1 | ForEach {
write-host $_.Fullname
Start-Process $_.Fullname -ArgumentList '/Extract="YES" /DIR=$Extracted\$DriverPKGFolder' -Wait
}

问题:单引号包裹的参数中变量不会被PowerShell解析,$Extracted和$DriverPKGFolder会被当作字面量直接传递给exe程序,导致程序无法识别正确路径。

第二种写法

$Extracted = "C:\Temp2\Extracted" 
$DriverPKGFolder = Read-Host -Prompt "enter the name of the folder the extraction will create"
Get-ChildItem -Path c:\temp2\driverdownloads -Filter *.exe -Depth 1 | ForEach {
write-host $_.Fullname
Start-Process $_.Fullname -ArgumentList '/Extract="YES" /DIR=$("$Extracted\$DriverPKGFolder")' -Wait
}

报错截图:
报错截图1
问题:子表达式语法错误,转义引号的方式不符合PowerShell规则,导致变量无法被正确解析,程序收到的路径格式混乱。

第三种写法

$Extracted = "C:\Temp2\Extracted" 
$DriverPKGFolder = Read-Host -Prompt "enter the name of the folder the extraction will create"
Get-ChildItem -Path c:\temp2\driverdownloads -Filter *.exe -Depth 1 | ForEach {
write-host $_.Fullname
Start-Process $_.Fullname -ArgumentList '/Extract="YES" /DIR="$Extracted\$DriverPKGFolder"' -Wait
}

报错截图:
报错截图2
问题:双引号嵌套导致程序无法识别完整路径,从截图可见路径被截断或格式错误。


正确解决方案

要让PowerShell正确解析变量,同时保证驱动提取exe能识别合法路径,推荐以下两种写法:

方式1:提前拼接路径,用单引号包裹避免嵌套问题

$Extracted = "C:\Temp2\Extracted" 
$DriverPKGFolder = Read-Host -Prompt "请输入提取后生成的文件夹名称"
# 用Join-Path可靠拼接路径,自动处理分隔符
$targetPath = Join-Path -Path $Extracted -ChildPath $DriverPKGFolder
# 提前创建目标文件夹,避免程序因路径不存在报错
if (-not (Test-Path -Path $targetPath)) {
    New-Item -Path $targetPath -ItemType Directory | Out-Null
}

Get-ChildItem -Path c:\temp2\driverdownloads -Filter *.exe -Depth 1 | ForEach-Object {
    Write-Host $_.FullName
    Start-Process -FilePath $_.FullName -ArgumentList "/Extract=YES /DIR='$targetPath'" -Wait
}

方式2:用转义双引号实现参数内的路径包裹

$Extracted = "C:\Temp2\Extracted" 
$DriverPKGFolder = Read-Host -Prompt "请输入提取后生成的文件夹名称"
$targetPath = Join-Path -Path $Extracted -ChildPath $DriverPKGFolder
if (-not (Test-Path -Path $targetPath)) {
    New-Item -Path $targetPath -ItemType Directory | Out-Null
}

Get-ChildItem -Path c:\temp2\driverdownloads -Filter *.exe -Depth 1 | ForEach-Object {
    Write-Host $_.FullName
    # 用`转义双引号,确保PowerShell解析变量后,exe能识别带引号的路径
    Start-Process -FilePath $_.FullName -ArgumentList "/Extract=`"YES`" /DIR=`"$targetPath`"" -Wait
}

关键注意点

  • 优先用Join-Path拼接路径,避免手动拼接\带来的格式问题
  • 提前创建目标文件夹,多数驱动提取exe不会自动创建不存在的路径
  • 不同厂商的驱动提取exe参数格式可能有差异,若仍报错需确认exe的官方提取参数规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:51:00