windows - 将命令输出保存到变量不起作用
问题描述
我想创建一个简单的脚本来在 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
解决方案
呃 - 很抱歉没有尽快发现真正的问题:您还必须=
在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"
返回包含Key
OR 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%---
推荐阅读
- java - 多个 Feign 客户端超时配置
- image-processing - YOLO-V4 中输入图像像素值如何缩放?
- django - 如何在 Django REST 框架中隐藏 POST 表单?
- c# - 使用 MailKit 的单个 SMTP 事务向多个收件人发送电子邮件
- python - 按组过滤,其中熊猫系列值增加
- python-3.x - python websocket中的回调函数出错:第346行,_callback回调(self,*args)
- java - Aeron 基本发布/订阅对在同一主机上连接,跨主机失败
- json - 在json正文中发送多个文件
- performance - 在执行相同的转换集时,ADF 映射数据流的性能与 Databricks 相比非常低
- haskell - 如何使用自定义的 `parseJSON` 解码 JSON - 一个函数而不是与 `fromJSON` 的实例相关的函数?