CreateObject("Wscript.Shell") 全局不起作用

CreateObject("Wscript.Shell") globally does not work

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

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,我会得到同样的错误。我该如何解决?

我设法在本地复制了您的问题,我发现 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

相反。