全局不能使用CreateObject(" Wscript.Shell")

时间:2016-11-02 10:57:13

标签: windows vbscript windows-7

我正在尝试创建一个运行如下命令的函数:

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

工作正常,但后来我想在更高级别使用objShell,所以我决定将objShell设为全局:

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

但是,现在当我运行它时,我收到错误:

WshShell.Exec: Access is denied.

它引用了行set objShell = CreateObject("Wscript.Shell")。如果我尝试使两个不同的变量objShell和objShell2我得到相同的错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

我设法在本地复制您的问题我发现WScript.Shell的范围没有错。

试试这个,它很可能会起作用(注意注释掉的行);

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

Access Denied错误似乎与调用objShell.CurrentDirectory有关。

问题是您正在尝试将当前目录传递给objShell.Exec()并且它不知道如何执行它(毕竟它不是应用程序)

这是一个最简单的例子;

CreateObject("Wscript.Shell").Exec("C:\")

输出:

WshShell.Exec: Access is denied.

如果您只想使用脚本输出当前目录,可能需要使用

print objShell.CurrentDirectory

代替。