批量 WMIC 重定向输出并包装到变量中 [英] Batch WMIC redirecting output and wrapping into variable

查看:19
本文介绍了批量 WMIC 重定向输出并包装到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 WMIC 删除旧打印服务器上的一些旧打印机

I'm trying to use WMIC to remove some old printers on our older print servers

如果我从命令行使用以下语法,它就可以工作

if I use the below syntax from the command line it works

WMIC 打印机,其中SERVERNAME LIKE '%%OLDSERVERNAME%%'"删除

WMIC PRINTER WHERE "SERVERNAME LIKE '%%OLDSERVERNAME%%'" DELETE

我被要求看看是否可以更换打印机或更新它们,以免帮助台收到如何添加打印机"的电话

I was asked to see if I could make it replace the printers or update them to spare the helpdesk from getting "how do I add my printer" calls

我尝试使用 SET 进行一些变体来设置 SERVERNAME 的属性,它似乎正在处理,但没有任何变化,执行 GET 操作仍会显示旧值.

I tried some variation with SET to set the properties for SERVERNAME, it appear to process, but nothing changes and doing a GET shows the old value still.

所以我想我可以做一个 FOR/F 循环,将打印机的名称(共享名)包装在一个变量中,然后在删除有问题的打印机后使用另一个命令重新创建打印机.

so I figured I could do a FOR /F loop, wrap the name of the printer (sharename) in a variable and then use another command to recreate the printers, after the offending printers have been deleted.

这是我的脚本

@ECHO

ECHO Gathering Installed Printer Information...

FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO SET PRINTERNAME=%%A

ECHO %PRINTERNAME%

所以你会认为你会把所有的值都包裹在一个很好的变量中,你可以随意处理,但没有,我打开了回显,看起来变量一被捕获就被设置回 null

so you would think you'd get the value all wrapped up in a nice variable to do with as you wish but no, I turned echo on and it appears that the variable gets set back to null as soon as it's captured

我的输出看起来像这样...

my output looks like this...

FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO SET PRINTERNAME=%%A

SET PRINTERNAME=nameofprinter

SET PRINTERNAME=

ECHO

ECHO is on.

想知道为什么它似乎在倾倒字符串.

would love some thoughts on why it seems to be dumping the string.

Powershell 和 VBScript 也不是不可能的,我对两者都很熟悉,只是这似乎是可能的,我真的不想重新开始.

Powershell and VBScript aren't out of the option either, I'm familar with both, just this seemed possible, and I really don't want to start over.

推荐答案

WMIC 返回两行,一行包含打印机名称,另一行为空.
解决这个问题的方法是测试空行.

WMIC is returning two lines, one with the printername, and one empty.
The solution to this is to test for empty lines.

ECHO Gathering Installed Printer Information...
FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO if not "%%A"=="" SET PRINTERNAME=%%A
ECHO %PRINTERNAME%

这篇关于批量 WMIC 重定向输出并包装到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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