【发布时间】:2016-11-14 21:02:45
【问题描述】:
我一直在尝试执行一个 PowerShell 函数 (countLines),该函数从 VBA 获取输入参数 fileName。我已经参考了this 和this 的一些答案,但它们对我不起作用。以下是我做同样的尝试(fname 是一个 VBA 变量,我将其作为参数发送到包含以下代码行的 VBA 例程):
fileReader.ps1的内容是:
function countLines {
param([string]$logFile);
#The directory path may differ for others according to the machine's source code repository
$scriptPath = Resolve-Path "..\..\testFolder";
$varHolder = -join($scriptPath, "\logFileCount.txt");
$linesb4Exec = Get-Content $logFile;
$nLines = $linesb4Exec.Count;
Clear-Content $varHolder
$nLines | Out-File $varHolder
#For second attempt, I am adding the following too
#echo $nLines;
}
第一次尝试:
Call Shell("powershell -ExecutionPolicy Unrestricted ""D:\Temp\fileReader.ps1"";countLines -fileName """ & fname & """", vbMaximizedFocus))
第二次尝试:
Dim strCommand As Variant, WshShell As Variant, WshShellExec As Variant, output As Variant
strCommand = "powershell -command ""& { . ""D:\Temp\fileReader.ps1"";countLines -logFile """ & fname & """ }"""
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Run(strCommand)
output = WshShellExec.StdOut.ReadAll
使用这个,我得到一个错误:类型不匹配。
第三次尝试(我尝试硬编码我的 PowerShell 文件中的所有内容并删除了该函数并只运行了一段代码):
Call Shell("powershell -ExecutionPolicy Bypass -file ""D:\Temp\fileReader.ps1""", vbMaximizedFocus)
并将上面的 powershell 脚本更改为:
$logFile = "C:\somepath\Logs\Log.txt";
$varHolder = "D:\testing\testFolder\logFileCount.txt";
$linesb4Exec = Get-Content $logFile;
$nLines = $linesb4Exec.Count;
Clear-Content $varHolder
$nLines | Out-File $varHolder
这似乎有效。
如果有人可以帮助我使用 VBA 调用任何带参数的 PowerShell 函数,我会很高兴。
【问题讨论】:
标签: excel powershell parameter-passing vba