6

我想从 Excel VBA 调用 Powershell 脚本并传递 1 个参数。如果没有 VBA,脚本可以完美运行并执行它应该做的事情。一旦调用工作,我想添加 1 个参数,但首先是成功调用...

但我无法在 Excel VBA 中调用它。首先向您展示我的 Powershell 脚本:

#param([string]$server)
$server = "chvmes01"

$BasicPath = Split-Path $script:MyInvocation.MyCommand.Path

write-host $BasicPath

Invoke-Command -FilePath $BasicPath\IISReport.ps1 -ComputerName $server

Read-Host "Return drücken..."

在 VBA 中,我创建了以下代码:

strCommand = "Powershell.exe -ExecutionPolicy ByPass -NoExit -File """ & BasicPath & """, 1"
Set WsShell = CreateObject("WScript.Shell")
WsShell.Run (strCommand)

strCommand 看起来像这样:

Powershell.exe -ExecutionPolicy Unrestricted -NoExit -File "E:\Temp\Registry\EXCEL_ALLE\Version_AllFromExcel_Aktuell\IISReport\InvokeCommand.ps1", 1

像这样我得到以下错误: 在此处输入图像描述

我不知道我可以改变什么了,我阅读了很多论坛帖子并改变了不同的东西,但没有任何效果!

我尝试使用没有“”的 strCommand,如下所示:

strCommand = "Powershell.exe -ExecutionPolicy ByPass -NoExit -File " & BasicPath & ", 1"

我试过了

-ExecutionPolicy Unrestricted AND -ExecutionPolicy ByPass 

我试过有无

-NoExit

我也试过

Shell (strCommand)

正如我所提到的,脚本可以在没有 VBA 的情况下完美运行!有人可以在这里帮忙吗?

4

2 回答 2

7

我找到了解决方案!!

实际上,@Pᴇʜ 的评论让我找到了答案!

我混淆了

Set WsShell = CreateObject("WScript.Shell")
WsShell.Run (strCommand)

Shell (strCommand)

", 1" 仅适用于 Shell 命令。

我只需要将我的 strCommand 更改为

    strCommand = "Powershell.exe -ExecutionPolicy ByPass -NoExit -File " & BasicPath
    Set WsShell = CreateObject("WScript.Shell")
    WsShell.Run (strCommand)

及其工作!

现在我可以尝试将参数传递给powershell!非常感谢!

于 2018-10-19T09:05:07.263 回答
2

该错误似乎表明逗号被附加到路径的末尾。您可能只需要将其用单引号括起来。尝试这个:

strCommand = "Powershell.exe -ExecutionPolicy ByPass -NoExit -File '" & BasicPath & "'"
于 2018-10-19T08:37:48.777 回答