Fitzroy
Fitzroy

Reputation: 249

Calling PowerShell from VBScript - Missing Double Quote

I have a VBScript that calls powershell.exe using the Shell object's Exec method.

For the purpose of the question, I have extracted the troublesome bit of code from my script and simplified it.

The expected outcome of the script below is that PowerShell's Write-Host cmdlet will print the following:

Please save the file to "C:\test"

But the actual result is this:

Please save the file to C:\test"

The initial double quote surrounding the file path is missing.

Option Explicit

Dim strPsCommand, ps, objShell, objExec
Dim strStdOut, strStdErr
Dim strStringToPrint

strStringToPrint = "$text = @'" & vbCrLf & "Please save the file to ""C:\test\""" & vbCrLf & "'@"

strPsCommand = strStringToPrint & "; Write-Host $text"
ps = "powershell.exe -Command " & strPsCommand

Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec(ps)

' Close standard input before reading standard output.
objExec.StdIn.Close()

strStdOut = objExec.StdOut.ReadAll()
strStdErr = objExec.StdErr.ReadAll()

WScript.Echo strStdOut
WScript.Echo strStdErr

The code above uses a here-string (which is best suited for my script). However I have tried substituting this for a regular string but the result is the same. To do this, I changed the value of strStringToPrint as follows:

strStringToPrint = "$text = 'Please save the file to " & """" & "C:\test\" & """" & "'"

Upvotes: 1

Views: 347

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

You need to escape the double quotes around the path twice:

  • for VBScript
  • for the commandline (the Exec call)

The former is done by doubling the double quotes. For the latter you need backslashes. You already have a backslash before the double quotes after the path (although probably unintentional), but not before the double quotes before the path.

Change this:

strStringToPrint = "$text = @'" & vbCrLf & "Please save the file to ""C:\test\""" & vbCrLf & "'@"

into this:

strStringToPrint = "$text = @'" & vbCrLf & "Please save the file to \""C:\test\""" & vbCrLf & "'@"

or this (if you want the trailing backslash in the path):

strStringToPrint = "$text = @'" & vbCrLf & "Please save the file to \""C:\test\\\""" & vbCrLf & "'@"

Upvotes: 1

Related Questions