在 DOS 脚本中,有没有办法验证变量中是否存在字符串?
在 DOS 脚本中,如果我有一个变量字符串,如何判断该变量字符串中是否存在某个字符串? (我不想创建一个临时文件来完成此操作。我已经知道如何执行此操作。)FIND.exe 和 FINDSTR.exe 似乎都需要物理文件而不是变量。
我尝试了这个,但失败了:
C:\Users\me>findstr.exe "Program" %ProgramData%
In a DOS script, if I have a variable string, how do I get a true or false that a certain string exists within that variable string? ( I don't want to have to create a temp file to accomplish this. I know how to do that hack already.) FIND.exe and FINDSTR.exe both seem to require a physical file rather than a variable.
I tried this, but it fails:
C:\Users\me>findstr.exe "Program" %ProgramData%
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您尝试使用库存 Windows 安装 - 我认为这不能像您描述的那样使用 CMD.EXE 来完成,因为您将使用
IF
命令获得最接近的结果,但它并没有不支持包含,它只包含以下运算符:如果您可以使用这些运算符(而不仅仅是严格意义上的包含)来完成您想要做的事情。您还可以使用
FOR
命令来分割字符串并测试每个单独元素的匹配,尽管这看起来相当脆弱。由于您已将其标记为 PowerShell,因此我将冒险假设 PowerShell 脚本解决方案也是可以接受的。如果是这种情况,那么解决方案的演示就非常简单:
注意:在 PowerShell 中,
-contains
运算符用于测试集合成员资格,而不是子字符串匹配。您将需要对字符串对象使用Contains
方法或-like
或-match
运算符来执行所需的模式匹配。If you are trying to use a stock windows install - I don't think this can be accomplished as you describe using CMD.EXE as the closest you will get would be with the
IF
command, but it doesn't support a contains, it only contains the following operators:If you can get away with what you want to do using those operators (and not strictly just a contains). You can also use the
FOR
command to split your string and test your matches on each individual element, though that seems rather brittle.Since you have tagged this as PowerShell, I am going to go out on a limb and assume that a PowerShell script solution would be acceptable as well. If that is the case, then the solution is quite simple to demonstrate:
Note: In PowerShell, the
-contains
operator is used to test for set membership, not substring matching. You will want to use theContains
method on a string object or the-like
or-match
operators to perform the desired patter matching.在 DOSTIPS 论坛中发现了另一个想法:
Found another idea in the DOSTIPS forum:
不是
尝试。
如果匹配,%ERRORLEVEL% 将为 0,否则为 1,而
Instead of
try
If it matches, %ERRORLEVEL% will be 0, otherwise, 1.