Powershell/Excel: Check if a excel document contains macros

Hi,

this script can be used to check if excel contains some active code. It opens the excel file in an safe way and looks for VB content and write the full file path to the console if macros are found.

###############################################################################
#
# created: 27.04.2020 Michael info@michlstechblog.info
#
# https://docs.microsoft.com/de-de/office/vba/api/excel.application.automationsecurity
# https://docs.microsoft.com/de-de/dotnet/api/microsoft.office.tools.excel.workbook.hasvbproject?view=vsto-2017
# Recover VBA Password
# https://stackoverflow.com/questions/1026483/is-there-a-way-to-crack-the-password-on-an-excel-vba-project
#
###############################################################################
# Command line parameter
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true,Position=1)][alias("f")][string]$excelfile=$false
) 

if(!(Test-Path $excelfile))
{
	write-warning " File $excelfile does not exists"
	exit 255
}

$iReturnCode=1

$oExcelFile=Get-item $excelfile
$msoAutomationSecurityForceDisable=3

$oExcel = New-Object -ComObject "Excel.Application"
$oExcel.AutomationSecurity= $msoAutomationSecurityForceDisable	

$oExcel.Visible = $true
$oExcelDoc = $oExcel.Workbooks.Open($oExcelFile.FullName)

if($oExcelDoc.HasVBProject)
{
	write-host " MACRO(S) in File $excelfile detected"
} 
else
{
	$iReturnCode=0
}

$oExcelDoc.Close($true)
#Start-Sleep 1
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcelDoc)|out-null
$oExcelDoc=$null
#Start-Sleep 1
$oExcel.Quit()
#Start-Sleep 1
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcel)|out-null
$oExcel=$null
[GC]::Collect()
exit $iReturnCode

If you want to check all excel files in an folder try this

PS D:\  Get-childitem -Recurse -Include *.xlsx  D:\myFolder\ | foreach {.\ExcelHasMacros.ps1 $_}

Michael

Check if a excel file contains macros
ExcelHasMacros.ps1
Version: 1.0

Check if a excel file contains macros

Author:Michael
Category:Powershell Scripts
Date:April 27, 2020
1.5 KiB
562 Downloads
Details...

Leave a Reply Cancel reply