Reputation: 16321
I am trying to make a function that runs commands like this:
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
print runCommand("git --help")
function runCommand(commandStr)
set objShell = CreateObject("Wscript.Shell")
Set objExec = objShell.Exec(commandStr)
Do Until objExec.Status
Wscript.Sleep 10
Loop
runCommand = objExec.StdOut.ReadAll()
end function
sub print(str)
stdout.WriteLine str
end sub
That works fine, but then I want to use the objShell at a higher level, so then I decide to make objShell global:
set objShell = CreateObject("Wscript.Shell")
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
print runCommand(objShell.CurrentDirectory)
print runCommand("git --help")
function runCommand(commandStr)
Set objExec = objShell.Exec(commandStr)
Do Until objExec.Status
Wscript.Sleep 10
Loop
runCommand = objExec.StdOut.ReadAll()
end function
sub print(str)
stdout.WriteLine str
end sub
However, now when I run it I get the error:
WshShell.Exec: Access is denied.
And it references the line set objShell = CreateObject("Wscript.Shell")
. If I try to make two different variables objShell and objShell2 I get the same error. How do I resolve this?
Upvotes: 1
Views: 11746
Reputation: 16671
I managed to replicate your issue locally I found that the scope of WScript.Shell
is not at fault.
Try this and it will most likely work (notice the commented out line);
set objShell = CreateObject("Wscript.Shell")
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
'print runCommand(objShell.CurrentDirectory)
print runCommand("git --help")
function runCommand(commandStr)
Set objExec = objShell.Exec(commandStr)
Do Until objExec.Status
Wscript.Sleep 10
Loop
runCommand = objExec.StdOut.ReadAll()
end function
sub print(str)
stdout.WriteLine str
end sub
The Access Denied
error appears to be related to calling objShell.CurrentDirectory
.
The issue is you are trying to pass the current directory to objShell.Exec()
and it doesn't know how to execute it (after all it's not an application).
Here is an example in it's simplest form;
CreateObject("Wscript.Shell").Exec("C:\")
Output:
WshShell.Exec: Access is denied.
If you just wanted to output the current directory using your script you probably wanted to use
print objShell.CurrentDirectory
instead.
Upvotes: 4