在Windows 10 Shell脚本中将命令的输出分配给变量 [英] Assigning output of a command to a variable in Windows 10 shell script

查看:319
本文介绍了在Windows 10 Shell脚本中将命令的输出分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测Windows 10便携式计算机所连接的SSID,并根据检测到的SSID决定要做什么.我可以通过以下命令检测SSID:

I'm trying to detect the SSID that my Windows 10 laptop is connected to, and deciding what to do based on the detected SSID. I'm able to detect the SSID via the following command:

netsh wlan show interfaces | findstr /r "^....SSID"

此命令输出如下:

    SSID                   :my_ssid    

我正在尝试使用以下命令将此字符串输出分配给变量:

I'm trying to assign this string output to a variable with the following command:

set ssid=
for /f %%i in ('netsh wlan show interfaces | findstr /r "^....SSID"') do set ssid=%%i
echo SSID is "%ssid%"

但是,我不断收到以下错误消息:

However, I keep getting the following error message:

| was unexpected at this time.

有人知道为什么吗?

还可以剥离"SSID",:"和空白的netsh输出,以便仅获得"my_ssid"作为输出吗?

Also, is it possible to strip the netsh output of the "SSID", ":" and the whitespace so that I get only "my_ssid" as the output?

推荐答案

for循环中使用管道时,需要使用^对其进行转义.否则,解释器会认为您一直在传递整个循环,而for /f %%i in ('netsh wlan show interfaces是无效的语法.

When you use a pipe in a for loop, you need to escape it with a ^. Otherwise, the interpreter thinks you're piping the entire loop up to that point and for /f %%i in ('netsh wlan show interfaces isn't valid syntax.

for /f %%i in ('netsh wlan show interfaces ^| findstr /r "^....SSID"') do set ssid=%%i

这篇关于在Windows 10 Shell脚本中将命令的输出分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆