在PowerShell脚本中embeddedExcel VBA脚本

我编写了一个Powershell脚本,用于查询Exchange Online中的所有组,然后获取每个组的成员身份,并将每个组保存到单独的CSV文件。 这一切工作正常。 (为简洁起见,省略了一些不相关的部分):

$excelTemplate = "$($fileLocation)\group-breakout.xlsm" Copy-Item $excelTemplate "$($tempPath)\group-breakout-$($curDate).xlsm" # Creating Excel COM Object $excel = new-object -comobject excel.application $excelFile = Get-ChildItem -Path C:\temp\group-breakout -Include *.xlsm -Recurse # Gathering all groups: Write-Host "Getting all groups from Exchange Online..." $allGroups = Get-DistributionGroup | select Name, PrimarySmtpAddress, ManagedBy, MemberJoinRestriction $allGroups | Export-Csv "$($tempPath)\1-AllGroups.csv" -NoTypeInformation Write-Host "`tDone." # Gathering members for all groups Write-Host "Getting members for all groups from Exchange Online..." $allGroups | ForEach-Object { Get-DistributionGroupMember -Identity $_.Name | select DisplayName, Alias, PrimarySmtpAddress | Export-Csv "$($tempPath)\$($_.name.Replace("/","-")).csv" -NoTypeInformation } Write-Host "`tDone." # Calling macro in xlsm to merge the created csvs into a Excel spreadsheet Write-Host "Creating Spreadsheet..." $workbook = $excel.workbooks.open($excelFile) # Opening workbook $worksheet = $workbook.worksheets.item(1) # Selecting worksheet $excel.Run("ImportCSVs") # Calling macro $workbook.save() #Saving workbook $workbook.close() # Closing workbook $excel.quit() # Closing Excel COM Object [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null # Making sure Excel process is closed. 

我也有一个Excel VBA脚本通过COM对象访问,将采取这些CSV并将它们添加到一个XLSX与每个CSV是一个工作表:

 Sub ImportCSVs() Dim fPath As String Dim fCSV As String Dim wbCSV As Workbook Dim wbMST As Workbook Set wbMST = ThisWorkbook fPath = "C:\temp\group-breakout\" 'path to CSV files, include the final \ Application.ScreenUpdating = False 'speed up macro Application.DisplayAlerts = False 'no error messages, take default answers fCSV = Dir(fPath & "*.csv") 'start the CSV file listing On Error Resume Next Do While Len(fCSV) > 0 Set wbCSV = Workbooks.Open(fPath & fCSV) 'open a CSV file wbMST.Sheets(ActiveSheet.Name).Delete 'delete sheet if it exists ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count) 'move new sheet into Mstr Columns.AutoFit 'clean up display fCSV = Dir 'ready next CSV Loop Worksheets("1-AllGroups").Activate Worksheets("placeholder").Delete Workbooks.Application.ActiveWorkbook.SaveAs Filename:="C:\temp\group-breakout\group-breakout.xlsx", FileFormat:=51 Application.ScreenUpdating = True Set wbCSV = Nothing End Sub 

我遇到的问题是必须在脚本位置包含启用了Excelmacros的电子表格,以便可以从脚本访问它。 有没有办法将VBA脚本embedded到Powershell脚本中并在Excel中运行? 或者,也可以直接使用Powershell来执行VBA脚本中的任务?