【问题标题】:CreateObject("Wscript.Shell") globally does not work全局 CreateObject("Wscript.Shell") 不起作用
【发布时间】:2016-11-02 10:57:13
【问题描述】:

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

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

【问题讨论】:

  • 在这种情况下,您需要去掉函数开头的“set objShell = CreateObject("Wscript.Shell")”!不要做两次!
  • @duDE 对不起,那是一个类型-o。删除。行为仍然失败。我错过了我还添加的打印功能。

标签: windows vbscript windows-7


【解决方案1】:

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

改为。

【讨论】:

  • 啊...是的,这行得通! - 我认为我在做一些愚蠢的事情......我试图在我的调用函数中使用 objShell.CurrentDirectory 的输出,我认为这里肯定存在资源双重使用。我现在已经把它分开了,效果很好:)。没有像样的 IDE 很难:o
  • @code_fodder 是的,你试图通过 runCommand() 函数传递 objShell.CurrentDirectory 会出错,因为 objShell.Exec() 不知道如何处理它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
相关资源
最近更新 更多