我试图将下面命令的结果分配给变量。目标是获得PID号。
SERVICE_NAME: msftpsvc
TYPE : 10 WIN32_OWN_PROCESS
STATE : 3 STOP_PENDING
(STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
PID : 7888
FLAGS :
如果你们都有更好的主意,请告诉我。但我试图删除所有空格,制表符,回车等...以便我可以搜索“PID:”字符串和“FLAGS”,然后复制PID编号。
我无法移除空格并将所有内容都放在一个字符串中。这是我的代码:
Dim wshShell
Set wshShell = WScript.CreateObject("WScript.Shell")
Dim CommandToRun, ScriptStdOut, ScriptStdErr, ExitCode
Dim results
CommandToRun = "sc.exe queryex msftpsvc"
ExitCode = ExecScript(CommandToRun)
results = Replace(ScriptStdOut, vbCrLf, "") 'this works
results = Replace(results, vbTab, "") 'nothing happens
results = Trim(results) 'nothing happens
Function ExecScript(Command)
Dim WshShellExec
Set WshShellExec = WshShell.Exec("cmd /c " & Command)
Dim ErrorRead
ScriptStdOut=""
ScriptStdErr=""
Do While WshShellExec.Status = 0
Do While Not WshShellExec.StdOut.AtEndOfStream
ScriptStdOut=ScriptStdOut&WshShellExec.StdOut.ReadAll()
Loop
Do While Not WshShellExec.StdErr.AtEndOfStream
ErrorRead = true
ScriptStdErr=ScriptStdOut&WshShellExec.StdErr.ReadAll()
Loop
Loop
ExecScript=WshShellExec.ExitCode
wscript.echo ScriptStdOut
Set WshShellExec=nothing
End Function
谢谢
答案 0 :(得分:1)
输出中没有选项卡,Trim
只是从字符串的开头和结尾删除空格,而不是从中间的某处删除空格。由于在您的情况下,SERVICE_NAME
之前或多行字符串的最后一个冒号之后没有空格,Trim
无法删除。
用正则表达式做这种替换会更好:
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
results = Trim(re.Replace(ScriptStdOut, " "))
以上内容将用一个空格替换所有连续的空格(换行符,制表符,空格等),然后删除任何剩余的前导或尾随空格。
但是,由于您的实际目标是获取服务的PID,因此我强烈建议完全放弃此方法并切换到WMI:
Set wmi = GetObject("winmgmts://./root/cimv2")
qry = "SELECT * FROM Win32_Service WHERE Name = 'msftpsvc'"
For Each svc In wmi.ExecQuery(qry)
pid = svc.ProcessId
Next
WScript.Echo pid