gpt4 book ai didi

powershell - 使用变量从批处理文件调用powershell替换

转载 作者:行者123 更新时间:2023-12-03 01:25:53 26 4
gpt4 key购买 nike

我需要用批处理文件中的 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 , 注意 % 的替换与 !在变量中也是 !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` 在正确的位置。

关于powershell - 使用变量从批处理文件调用powershell替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63069362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com