gpt4 book ai didi

windows - "findstr"在 VBScript 中总是返回失败

转载 作者:可可西里 更新时间:2023-11-01 10:39:32 26 4
gpt4 key购买 nike

上下文
我正在尝试为自己编写一个脚本,根据条件切换我的 WLAN 适配器(启用/禁用它)。如果适配器当前已启用,则脚本应禁用它,或者相反,如果当前已禁用,则启用它。这是我到目前为止想出的:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%comspec% /C devcon status PCI\VEN_168C > C:\devstat.txt", 0, false
Return = WshShell.Run("findstr disabled C:\devstat.txt", 0, true)
WScript.Echo Return

If Return = 0 Then
WshShell.Run "devcon " & "enable PCI\VEN_168C", 0, false
Else
WshShell.Run "devcon " & "disable PCI\VEN_168C", 0, false
End If


脚本说明
第 1 行非常明显,所以我跳过了那部分。 第 2 行 执行 devcon 以检查我的 WLAN 适配器(硬件 ID PCI\VEN_168C)的状态并将输出转储到 C:\devstat.txt第 3 行 运行 findstr 以检查 C:\devstat.txt 是否包含“disabled”。如果未找到“disabled”,findstr 应返回 errorlevel > 0,否则 errorlevel == 0(零)。脚本的其余部分只是基于 Return 值(应该包含 errorlevel 的值)的 if 语句。

问题
Return 的值始终为 1,无论 C:\devstat.txt 是否包含“disabled”。 p>

我在这里错过了什么?


最终编辑
感谢 barlop 的提示,我设法找到了解决方法。原来罪魁祸首是Windows Scripting Host。该脚本在执行 第 2 行 后必须暂停几毫秒,因此最终脚本应如下所示:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%comspec% /C devcon status PCI\VEN_168C > C:\devstat.txt", 0, false
WScript.sleep 400
Return = WshShell.Run("findstr disabled C:\devstat.txt", 0, true)
Rem WScript.Echo Return

If Return = 0 Then
WshShell.Run "devcon " & "enable PCI\VEN_168C", 0, false
Else
WshShell.Run "devcon " & "disable PCI\VEN_168C", 0, false
End If

最佳答案

findstr没有问题..

运行此代码,它与您的代码相同,但在 findstr 行之前带有 wscript.echo“WAIT”。现在,当执行 wscript.echo "WAIT"行时,打开文件,您可能会看到它不包含 disabled,现在在其中写入 disabled,然后保存。然后对显示等待的消息单击确定。程序继续进行。

我从 findstr 命令返回的错误级别得到了正确的结果。那就是
1 表示不包含 disabled
0 表示何时发生

您也可以为了故障排除而尝试,让程序更容易找到错误。所以您可以尝试删除该行以测试 findstr,然后您可能会发现 findstr 没问题。查看 findstr 之前的文件并手动修改它,也可以显示它而无需删除该行。

我也尝试将 Return 更改为 Retur,因为我认为 Return 可能是一个关键字,因此不太有效,但它与您使用的 Return 变量名称配合使用效果很好。

所以问题是

WshShell.Run "%comspec% /C devcon status PCI\VEN_168C > C:\devstat.txt", 0, false

但是 findstr 没问题。我认为你在

中使用 True 作为第三个参数是正确的

WshShell.Run("findstr xbc C:\getmail\a.a", 0, true)

自 script56.chm 文档“如果设置为 true,脚本执行将暂停,直到程序完成,并且 Run 返回程序返回的任何错误代码。如果设置为 false(默认值),Run 方法会在之后立即返回启动程序,自动返回 0(不被解释为错误代码)。”

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%comspec% /C devcon status PCI\VEN_168C > C:\devstat.txt",

0, false
wscript.echo "WAIT"
Return = WshShell.Run("findstr disabled C:\devstat.txt", 0, true)
WScript.Echo Return

If Return = 0 Then
WshShell.Run "devcon " & "enable PCI\VEN_168C", 0, false
Else
WshShell.Run "devcon " & "disable PCI\VEN_168C", 0, false
End If

关于windows - "findstr"在 VBScript 中总是返回失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893411/

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