Max
Max

Reputation: 1299

Trying to remove all spaces, tabs, carriage returns using VBScript

I am trying to assign the results of the command below into a variable. The goal is to obtain the PID number.

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              :

If you all have a better idea let me know. But I was trying to remove all the spaces, tabs, carriage returns, etc... so that I could search for the "PID:" string and "FLAGS" and then copy the PID number.

I haven't been able to remove the spaces and have everything in one single string. Here is my code:

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

Thank you

Upvotes: 0

Views: 4637

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200253

There are not tabs in the output, and Trim just removes spaces from beginning and end of a string, not from somewhere in the middle. Since in your case there are no spaces before SERVICE_NAME or after the last colon of the multiline string there's nothing for Trim to remove.

It's better to do this kind of replacement with a regular expression:

Set re = New RegExp
re.Pattern = "\s+"
re.Global  = True

results = Trim(re.Replace(ScriptStdOut, " "))

The above will replace all consecutive whitespace (linebreaks, tabs, spaces, etc.) with a single space, and then remove any remaining leading or trailing space.

However, since your actual goal is to obtain the PID of the service, I'd strongly recommend to drop this approach entirely and switch to 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

Upvotes: 2

Related Questions