我需要用批处理文件中的 xml 文件中的用户输入替换字符串,我通过使用 powershell“replace”命令并从批处理中调用它来使其工作,但我无法弄清楚如何在 powershell 中使用批处理变量命令。
在职的 :
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','somePassword' | Out-File -encoding ASCII tempProfile.xml"
不工作:
set /p pwd="Enter pwd: "
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','%pwd%' | Out-File -encoding ASCII tempProfile.xml"
信息:我使用的是 Windows 7
编辑:使用更简单的脚本,它可以工作,所以问题似乎来自我脚本中的其他地方(亮度部分工作正常)。
for /f "tokens=3" %%i in ('netsh wlan show interface ^| findstr /i "SSID"') do set "myssid=%%i" & goto next
:next
set "myssid=%myssid: =%"
if /i "%myssid%"=="someSSID" (
set "brightness=80"
) ELSE (
set "brightness=30"
set /p pwd="Enter pwd: "
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','%pwd%' | Out-File -encoding ASCII tempProfile.xml"
pause
)
CALL "brightness.bat" "%brightness%"
测试和真实脚本之间的执行顺序似乎不同。这是工作测试脚本:
set /p pwd="Enter pwd: "
echo %pwd%
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','%pwd%' | Out-File -encoding ASCII tempProfile.xml"
pause
有了它的输出:
>set /p pwd="Enter pwd: "
Enter pwd: hell
>echo hell
hell
>powershell -Command "(gc personalWifiProfile.xml) -replace 'password','hell' | Out-File -encoding ASCII tempProfile.xml"
>pause
Appuyez sur une touche pour continuer...
以及完整脚本的输出:
>for /F "tokens=3" %i in ('netsh wlan show interface | findstr /i "SSID"') do set "myssid=%i" & goto next
>set "myssid=mySSID" & goto next
>set "myssid=mySSID"
>if /I "mySSID" == "SomeSSID" (set "brightness=80" ) ELSE (
set "brightness=30"
set /p pwd="Enter pwd: "
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','' | Out-File -encoding ASCII tempProfile.xml"
pause
)
Enter pwd: 123
Appuyez sur une touche pour continuer...
您需要delayedexpansion
,请注意变量中的%
with替换:!
!pwd!
setlocal enabledelayedexpansion
if /I "mySSID" == "SomeSSID" (
set "brightness=80"
) ELSE (
set "brightness=30"
set /p pwd="Enter pwd: "
powershell -Command "(gc personalWifiProfile.xml) -replace 'password','!pwd!' | Out-File -encoding ASCII tempProfile.xml"
pause
)
我只显示了与您的问题相关的部分代码,因此setlocal
如果您有其他代码块设置和使用变量,请确保将enabledelayedexpansion放置在正确的位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句