我一直在嘗試執行從VBA獲取輸入參數fileName
的PowerShell功能(countLines
)。我提到了this和this的一些答案,但他們不適合我。以下是我嘗試做相同的(fname
是我送的參數包含代碼的下面一行VBA程序的VBA變量):如何使用VBA傳遞參數來執行PowerShell功能
的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函數,我將很高興。
哎呀...對不起,我的壞...我會盡快編輯它...謝謝指出 – Rishi
這工作! :)而且你隱含地解決了我忘記問的一個疑問,那就是如何阻止PowerShell窗口自動關閉。我無法確定路徑沒有得到解決的問題,你正確地指出了這一點......布拉沃爲這樣一個很好的描述性答案!我需要做大量的閱讀...... – Rishi
如果您可以指定如何正確捕獲我的VBA中的PowerShell函數的返回值,那將會很棒。正如您已經指出的那樣,使用上面的返回值實際上會將我退出代碼,所以這對我不起作用。 – Rishi