如何用PowerShell读取多个.bin.sup文件内容并传入命令循环执行
解决方案:读取.bin.sup文件内容并传入命令执行
你的核心问题在于误用start启动Notepad来读取文件内容——start仅用于打开外部程序,无法将文件内容存入变量;同时第二个循环重复遍历设备ID列表,逻辑完全错误。正确的做法是直接用PowerShell的Get-Content命令读取文件内容,无需借助Notepad。
修正后的完整代码
$filePath = "C:\Users\Administrator\Documents\tools\DeviceNames.txt" $softwarePath = "C:\Users\Administrator\Desktop\soft\software.exe" $pythonPath = "C:\Python27\python.exe" foreach ($deviceId in Get-Content $filePath ) { Write-Host "Processing drive $deviceId" # 生成.bin和.bin.sup文件 & $softwarePath -K -o zsup -f "${deviceId}.bin" -n $deviceId & $pythonPath tss.py --sup="" "${deviceId}.bin" # 构造当前设备对应的.bin.sup文件路径 $supFilePath = "${deviceId}.bin.sup" # 检查文件是否存在,避免因生成失败导致报错 if (Test-Path -Path $supFilePath -PathType Leaf) { # 读取文件内容到变量,Trim去除多余换行/空白字符 $code = (Get-Content -Path $supFilePath -Raw).Trim() # 执行目标命令 & .\software.exe -K -o supauth -p $code -n $deviceId Write-Host "Completed supauth for $deviceId" } else { Write-Warning "File $supFilePath not found for device $deviceId" } }
关键细节说明
- 用
Get-Content -Raw直接读取文件全部内容,搭配Trim()确保变量$code是纯净的目标字符串(去除可能的换行符或空白)。 - 新增
Test-Path检查文件是否存在,避免因前序步骤生成失败导致后续命令报错。 - 将变量名从
$line改为$deviceId,提升代码可读性。 - 使用
&调用外部程序,是PowerShell中执行外部命令的标准写法,可规避路径含空格时的执行问题。
内容的提问来源于stack exchange,提问作者Raven
相关产品推荐
相关产品推荐

