Tlicous
Tlicous

Reputation: 21

Inserting a variable in wsh.run command string

I want to have my VBScript input variable used in my
makefile = objShell.run (""""""cmd /K CD "strFolderName" & dir /-n > "strFolderName"\wk3result.txt"""""",1,True) command.

I've tried cmd /K cd '"strFolderName"'… I get directory not found so I do not believe my variables strFolder name is being put into the cmd line code correctly.

Here is my script:

Const cTitle = "WK3 Assignment"

Dim objFSO, objFolder
Dim strFolderName, objShell
strFolderName = InputBox("Which Folder", cTitle)

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFolder = objFSO.GetFolder(strFolderName)

If objFSO.FolderExists(strFolderName) Then
    WScript.Echo "Folder is there"
Else
    WScript.Echo "Folder is not there"
End If


Set objShell = WScript.CreateObject("WScript.shell")
makefile = objShell.run (""""""cmd /K CD "strFolderName" & dir /-n >      "strFolderName"\wk3result.txt"""""",1,True)

expecting to get a txt file with the dir results of the inputed folder

Upvotes: 2

Views: 755

Answers (1)

Étienne Laneville
Étienne Laneville

Reputation: 5021

You are missing some & around your strFolderName variable in your makefile command string. It should look like this:

"cmd /K CD """ & strFolderName & """ dir /-n > """ & strFolderName & "\wk3result.txt"""

Entire command:

makefile = objShell.run ("cmd /K CD """ & strFolderName & """ dir /-n > """ & strFolderName & "\wk3result.txt""", 1, True)

Better yet, make a variable of your command in case you need to view it for troubleshooting:

Dim strCommand
strCommand = "cmd /K CD """ & strFolderName & """ dir /-n > """ & strFolderName & "\wk3result.txt"""
makefile = objShell.run(strCommand, 1, True)

This way you can check what the command is with MsgBox strCommand.

Upvotes: 1

Related Questions