无法从Windows服务运行VBScript

我有一个Windows服务,该服务调用bat文件。该bat文件将调用PowerShell脚本,在该PowerShell脚本中将调用VBScript。

Windows Service > bat file > powershell file > vbscript

当我手动运行bat文件时,成功执行了VBscript,但是如果我从Windows服务中执行了相同的bat文件,则将调用所有脚本,但是VBScript会跳过运行。

手动执行bat文件可以成功执行VBScript,但不能通过Windows服务

我试图以不同的方式在PowerShell中调用VBScript:

  1. & c:\windows\system32\cscript.exe NameOfFile.vbs
  2. start-process
  3. invoke-expression
  4. C:\Windows\System32\cscript.exe NameOfFiles.vbs //B //Nologo $IP_SU $RemoteSessions_Output $user

我的VBScript是:

dim ip
dim sessions_dir
dim temp
dim username
dim password

set temp = Wscript.Arguments
ip = temp(0)
sessions_dir = temp(1)
username = temp(2)
password = temp(3)

Sub WaitEnter()
    WshShell.Appactivate("telnet " & ip )
    WScript.Sleep 2000
    WshShell.Appactivate("telnet " & ip)
    WshShell.SendKeys "{Enter}"
    WshShell.Appactivate("telnet " & ip)
    WScript.Sleep 2000
End Sub

set WshShell = WScript.CreateObject("WScript.Shell")
Wscript.Sleep 1000
WshShell.Appactivate("telnet " & ip )
WshShell.Run "telnet " & ip & " -f " & sessions_dir & "\" & ip & "_SU_Status_Output.txt",2
WshShell.Appactivate("telnet " & ip)
WScript.Sleep 1000
WshShell.Appactivate("telnet " & ip)
WshShell.SendKeys username
WaitEnter

WshShell.Appactivate("telnet " & ip)
WshShell.SendKeys password
WaitEnter

WshShell.Appactivate("telnet " & ip)
WshShell.SendKeys "SU_INrOmk=` pl | awk '{{}print {$}3{}}' | head -3 | cut -d '=' -f2`; SU_type=` pl | grep $SU_INrOmk | tail -1 | awk '{{}print {$}12{}}'`"
WaitEnter

WshShell.Appactivate("telnet " & ip)
WshShell.SendKeys "echo $SU_type"
WaitEnter

WshShell.Appactivate("telnet " & ip)
WshShell.SendKeys "exit"
WshShell.Appactivate("telnet " & ip)
WshShell.SendKeys "{Enter}"

和调用它的PowerShell脚本如下:

if(Test-Path C:\Windows\System32\cscript.exe){
    echo "Cscript found"
    $command = "& C:\Windows\System32\cscript.exe NameOfFile.vbs $IP_SU $RemoteSessions_Output $user $DecPwd | out-null"
    Invoke-Expression -Command $Command
    start-Sleep 10
    if($?){
        start-sleep 10
        $SU_Output_File = $IP_SU + "_SU_Status_Output.txt"
        $SU_Remote_FilePath = $RemoteSessions_Output + "\" + $SU_Output_File
    }
}

我希望Windows服务调用bat文件时会调用VBScript。

xqhong0826 回答:无法从Windows服务运行VBScript

我在这里看到了可能会给您带来麻烦的几件事。

我不是VBS的高手,但我的猜测是,您使用的Wscript需要交互性,但您应该使用Cscript变体调用。我的猜测是您的脚本可能因此受到轰炸。自Vista / Windows Server 2008以来,服务无法在交互式上下文中运行。

您使用Invoke-Expression进行调用,即使cmdlet失败, (几乎)总是返回成功 。换句话说,即使命令失败,Invoke-Expression也会(几乎)始终将$?设置为$ True。但是,您可以在表达式的末尾插入; $?的求值,最终将按您的期望设置$?,这打破了“始终将$?设置为{ {1}}”。

但是,您也错误地使用了$True$?仅评估$?的成功,而不评估命令。 cmdlets是可执行文件,必须使用cscript.exe自动变量来评估其成功。对于成功,这通常是$LASTEXITCODE,对于不成功,通常是其他任何值。您必须亲自检查此0是否成功,因为即使$LASTEXITCODE设置为ErrorActionPreference,它也不会自动将非零退出代码视为终止错误。

超出此答案的范围,但值得一提的是I would recommend replacing Invoke-Expression with a straight call to the executable and splat your parameters instead

本文链接:https://www.f2er.com/3144909.html

大家都在问