Skip to content

Instantly share code, notes, and snippets.

@theonlyway
Last active January 18, 2022 10:41
Show Gist options
  • Save theonlyway/ce65c1b86813e7a0fbd20ddd450fb02e to your computer and use it in GitHub Desktop.
Save theonlyway/ce65c1b86813e7a0fbd20ddd450fb02e to your computer and use it in GitHub Desktop.
Loop through list of password protected excel files and save them as a csv with new name
# path to the files with a wildcard at the end
$sourcePath = "C:\Repos\excelpassword\*"
# place to save the files
$destPath = "C:\Repos\excelpassword"
# gets a list of all the files but only includes files with the .xlsx extension
$items = Get-ChildItem -Path $sourcePath -Include *.xlsx
# password for the file(s)
$password = 'T&4gh!$Tnw'
# Creates the excel object
$excel = New-Object -comobject Excel.Application
# hides the excel window
$excel.visible = $false
# specifies the suffix to apply
$suffix = "somesuffix"
# specifies the prefix to apply
$prefix = "someprefix"
# loops through all the files found one at a time
$i = 1
foreach ($item in $items)
{
Write-Host "Opening $($item.fullname) - $i out of $($items.count)"
# opens the workbook with the password
$workbook = $excel.Workbooks.open($item.fullname, 0, 0, 5, $password)
# replaces any dashes with underscores in the base name of the file
$baseNameReplaceDashes = ($item.basename).replace('-', '_').replace(' ', '_')
# builds the path and name of the new file based on the original files name and path which means it will save it along side the original but as a csv with the prefix and suffix
$newFileName = $destPath + '\' + $prefix + '_' + $baseNameReplaceDashes + '_' + $suffix + '.csv'
$activesheet = $workbook.ActiveSheet
$worksheet = $workbook.Worksheets.Item($activesheet.name)
# Named range called _custom
$datarange = $worksheet.Range("_custom")
# Copies the range to clipboard
$datarange.Copy()
# Creates a new workbook in memory
$destworkbook = $excel.Workbooks.Add()
$destsheet = $destworkbook.Worksheets.Item(1)
# Pastes the range to the A1 cell
$destsheet.Paste($destsheet.Range("A1"))
$excel.DisplayAlerts = 'False'
# saves it as a csv based on https://docs.microsoft.com/en-us/office/vba/api/excel.xlfileformat
Write-Host "Saving $newFileName"
# Writes out the workbook in memory to file instead of the original $workbook
$destworkbook.SaveAs($newFileName, 6)
# closes the file
$workbook.Close()
$destworkbook.Close()
$i++
}
# closes excel
$excel.quit()
@theonlyway
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment