【问题标题】:Call Powershell Script from VBA(with Parameter)从 VBA 调用 Powershell 脚本(带参数)
【发布时间】:2019-03-24 02:59:55
【问题描述】:

我想从 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 的情况下完美运行! 有人可以帮忙吗?

【问题讨论】:

  • 我不是很喜欢 powershell,但是当你在 PS 脚本中将 #param([string]$server) 更改为 #param([$server) 会发生什么?
  • 是的,我可以试试这个,但由于脚本不执行,我无法测试它是否有效。首先我们必须让执行工作...
  • 为什么最后有个", 1"?
  • 它为WindowStyle,1代表vbNormalFocus --> 窗口有焦点,恢复到原来的大小和位置。
  • 我找到了解决方案,检查我的答案,你引导我找到答案!非常感谢..

标签: excel vba powershell


【解决方案1】:

我找到了解决办法!!

其实@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!非常感谢!

【讨论】:

  • 正要发布它。 WsShell.Run (strCommand, 1) 应该是正确的。
  • 关闭... 但是 1 根本不需要,一个只需要它 对于 Shell 命令.. 我把它弄混了一点,这就是它不起作用的原因 ;) docs.microsoft.com/en-us/office/vba/language/reference/…
  • 但是 WsShell 也有窗口样式:WshShell.Run strCommand, [intWindowStyle], [bWaitOnReturn] 例如 0 用于隐藏,1 用于正常焦点……还有更多。
【解决方案2】:

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

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

【讨论】:

  • 我试过这个,但现在错误文本是:处理 -File ''E:\Temp\Registry\',' failed: The given path's format is not supported.为 -File 参数指定有效路径。这条路有什么问题??
  • 您确定在 VBA 中构建 BasicPath 变量的方式仍然有效吗?
  • ^ 之所以说上述路径不被支持,只是因为它当前没有指向.ps1 文件。所以是的,检查BasicPath 是否仍然具有文件的完整路径。你没有在你的问题中分享这一点,所以我很难说,但这是我的猜测。
  • BasicPath 看起来像这样 "E:\Temp\Registry\EXCEL_ALLE\Version_AllFromExcel_Aktuell\IISReport\InvokeCommand.ps1" 我不知道这应该是什么问题..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 2016-10-25
  • 2020-10-08
相关资源
最近更新 更多