使用管理员权限从 VBA 运行 Powershell

问题描述 投票:0回答:1

我无法使用管理员权限从 VBA 成功运行我的 PowerShell 脚本。

我已经检查了这个论坛中的各种答案并尝试适应但没有成功。

当我执行下面的VBA脚本时,有一个窗口将打开不到一秒然后关闭(我不知道它是Powershell还是命令窗口)并且脚本没有运行,如下所示没有完成它的工作,并立即完成(不等待十秒钟)。另外,没有任何内容写入

StdOut
StdErr

如果脚本从提升的命令窗口或提升的 Powershell 窗口运行,它将按设计运行。

该脚本旨在暂时断开网络适配器的连接。在此阶段已进行简化,并且仅适用于名为

Ethernet
的适配器。

Powershell 脚本

Disable-NetAdapter -name Ethernet -confirm:$false
Start-Sleep -Seconds 10
Enable-NetAdapter -name Ethernet -confirm:$false

运行提升的命令窗口代码

C:\PowerShell Scripts>"disable network temporarily.ps1"
enter image description here

无法运行的 VBA 代码

'Needs reference to Windows Script Host Object Model
Option Explicit
Sub TempNetworkDisable()
    Dim wshShell As wshShell
    Dim wshShellExec    As Object
    Dim strCommand      As String
    Dim strOutput

    strCommand = "pwsh.exe -c Start-Process -Verb RunAs pwsh.exe \"" -ExecutionPolicy Unrestricted -NoExit -f `\""C:\PowerShell Scripts\Disable Network Temporarily.ps1`\"""
    
    Set wshShell = New wshShell
    Set wshShellExec = wshShell.Exec(strCommand)
    strOutput = wshShellExec.StdOut.ReadAll()
    Debug.Print "StdOut:", strOutput

    strOutput = wshShellExec.StdErr.ReadAll()
    Debug.Print "StdErr:", strOutput
End Sub
  • Windows 11 专业版
    • 版本 10.0.22631 内部版本 22631
  • PS版本7.4.6
  • 适用于 Microsoft 365 MSO 的 Microsoft® Excel®(版本 2409 内部版本 16.0.18025.20160)64 位
  • VBA 7.1.1143
excel vba powershell
1个回答
0
投票

使用以下内容:

strCommand = "pwsh.exe -c Start-Process -Verb RunAs pwsh.exe '-ExecutionPolicy Bypass -NoExit -f \""C:\PowerShell Scripts\Disable Network Temporarily.ps1\""'"
© www.soinside.com 2019 - 2024. All rights reserved.