简体   繁体   中英

CreateObject(“Wscript.Shell”) globally does not work

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM