首页 > 解决方案 > 将命令输出保存到变量不起作用

问题描述

我想创建一个简单的脚本来在 Windows10 上显示 wlan 密码。对于不熟悉 cmd 命令的用户来说,这将是一个很好的解决方案。

在 Windows 7 上,它可以使用 GUI 完成,但在较新的操作系统上则不行。

我卡在了线上

for /f "tokens=*" %%j in ('netsh wlan show profile %ssid% key=clear ^| findstr "Key Content"') do set wlan_password=%%j

该变量wlan_password始终为空。即使我将set指令更改为例如echo,它也表明语法不正确。我无法解决这个问题。

为什么上面的行不起作用,但是行:

for /f "tokens=*" %%i in ('netsh wlan show interfaces ^| findstr "Profile"') do set wlan_output=%%i

效果很好?

@echo off
set wlan_output=
set connected_ssid=
set ssid=
set wlan_password=
for /f "tokens=*" %%i in ('netsh wlan show interfaces ^| findstr "Profile"') do set wlan_output=%%i
for /f "tokens=2 delims=:" %%a in ("%wlan_output%") do set connected_ssid=%%a
call :TRIM %connected_ssid% connected_ssid
set ssid=%1
if "%ssid%"=="" set /p "ssid=Podaj nazwe sieci [%connected_ssid%]: " || set "ssid=%connected_ssid%"
if not "%ssid%"=="" (
    for /f "tokens=*" %%j in ('netsh wlan show profile %ssid% key=clear ^| findstr "Key Content"') do set wlan_password=%%j

    echo "Haslo do sieci %ssid%: %wlan_password%"
    exit /b
)
else (
    echo "Nie podano nazwy sieci. Nie mozna odczytac hasla"
    exit /b
)
pause

exit /b
:TRIM
SET %2=%1
GOTO :EOF

标签: windowsbatch-filecmd

解决方案


呃 - 很抱歉没有尽快发现真正的问题:您还必须=for命令中转义:

for /f "tokens=*" %%j in ('netsh wlan show profile %ssid% key^=clear ^| findstr /c:"Key Content"') do set wlan_password=%%j
set wlan_password

注意:使用findstr /c:"Key Content"or find "Key Content",因为findstr "Key Content"返回包含KeyOR Content(或两者)的每一行。(并不是说在这种特殊情况下会有什么不同,但没有/c:它迟早会咬你)

仅获取密钥:

for /f "tokens=1,* delims=:" %%j in ('netsh wlan show profile %ssid% key^=clear ^| find "Key Content"') do set "wlan_password=%%k"
set "wlan_password=%wlan_password:~1%"
echo ---%wlan_password%---

推荐阅读