如何获取在Excel VBA中运行的Powershell脚本的返回值?

如何获取在Excel VBA中运行的Powershell脚本的返回值?,powershell,excel,return-value,vba,Powershell,Excel,Return Value,Vba,我正在使用Excel VBA运行一个简单的Powershell脚本,当它在Powershell中运行时,会返回给定目录中某些文件的一个或两个文件名 我可以从VBA运行此脚本,但返回值始终是某个随机整数。如何让脚本返回通过Powershell脚本返回的文件名 VBA调用脚本: Dim weekly As String weekly = Shell("Powershell ""<location of powershell script.ps1>"" ") Dim weekly作

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

我可以从VBA运行此脚本,但返回值始终是某个随机整数。如何让脚本返回通过Powershell脚本返回的文件名

VBA调用脚本:

 Dim weekly As String

 weekly = Shell("Powershell ""<location of powershell script.ps1>"" ")
Dim weekly作为字符串
每周=Shell(“Powershell”“”“”)
脚本:

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

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

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

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

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

我知道这已经太晚了,但我想让其他正在搜索的人也能这样做。 让您的powershell脚本编写输出文件:

Get-ChildItem "Directory to Search" | Select-String -Pattern "what to seach for" | out-file "C:\output.txt"
从那里,您可以逐行将此内容写入变量:

子测试()
Dim txtfile、text、textline作为字符串
txtfile=“C:\output.txt”
打开txtfile作为#1输入
直到EOF(1)为止
行输入#1,文本行
text=文本和文本行
环
关闭#1
MsgBox文本
端接头

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

我非常激动这项工作!但事实并非如此。你认为还有别的方法吗?