I have been trying to execute a PowerShell function (countLines
) that takes an input parameter fileName
from VBA. I have referred some answers from this and this but they are not working for me. The following are my attempts to do the same (fname
is a VBA variable that I am sending as a parameter to the VBA routine that contains the following line of codes):
The contents of fileReader.ps1
are:
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;
}
First Attempt:
Call Shell("powershell -ExecutionPolicy Unrestricted ""D:\Temp\fileReader.ps1"";countLines -fileName """ & fname & """", vbMaximizedFocus))
Second Attempt:
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
Using this, I am getting an error: Type Mismatch.
Third Attempt (I tried hardcoding everything in my PowerShell file and removed the function and just running a block of code):
Call Shell("powershell -ExecutionPolicy Bypass -file ""D:\Temp\fileReader.ps1""", vbMaximizedFocus)
and changing the above powershell script to:
$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
This seems to be working.
I will be glad if someone could help me to call any PowerShell function with parameters using VBA.