【问题标题】:How do I get the return value of a Powershell script that is run in Excel VBA?如何获取在 Excel VBA 中运行的 Powershell 脚本的返回值?
【发布时间】:2013-11-15 16:26:19
【问题描述】:

我正在使用 Excel VBA 运行一个简单的 Powershell 脚本,该脚本在 Powershell 本身中运行时,会返回给定目录中某些文件的一个或两个文件名。

我可以从我的 VBA 运行这个脚本,但返回值总是一些随机整数。如何让脚本返回通过 Powershell 脚本返回的文件名?

VBA 调用脚本:

 Dim weekly As String

 weekly = Shell("Powershell ""<location of powershell script.ps1>"" ")

脚本:

Get-ChildItem "<directory to search in>" | Where-Object {$_.Name -match "<regex to find file name>"}

如果我遗漏了任何细节,请询问。

【问题讨论】:

    标签: powershell excel return-value vba


    【解决方案1】:

    看起来 VBA 只是看到了 powershell.exe 退出的退出代码。试试这个:

    Get-ChildItem "<directory to search in>" | Where-Object {$_.Name -match "<regex to find file name>"} 2>&1
    

    我相信这会将您的 Powershell 输出重定向到 VBA 应该能够获取的标准输出。

    【讨论】:

    • 我对它的工作感到非常兴奋!然而,事实并非如此。你认为可能有另一种方法吗?
    【解决方案2】:

    我知道这已经很晚了,但我想让其他人寻找这种方法来做到这一点。 让你的 powershell 脚本编写一个输出文件:

    Get-ChildItem "Directory to Search" | Select-String -Pattern "what to seach for" | out-file "C:\output.txt"
    

    从那里您可以将这一行逐行写入变量:

    Sub test()
    Dim txtfile, text, textline As String
    
    txtfile = "C:\output.txt"
    
    Open txtfile For Input As #1
    
    Do Until EOF(1)
        Line Input #1, textline
        text = text & textline
    Loop
    
    Close #1
    
    MsgBox text
    
    End Sub
    

    您可以从那里将文本插入到一个单元格中,或者如果愿意,您可以将每一行写入一个数组并在需要时单独选择每一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 2021-02-05
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      相关资源
      最近更新 更多