Skip to content

Instantly share code, notes, and snippets.

@roberocity
Created August 20, 2020 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roberocity/0702d9758ff190407e8501791a74317c to your computer and use it in GitHub Desktop.
Save roberocity/0702d9758ff190407e8501791a74317c to your computer and use it in GitHub Desktop.
Use PowerShell and Excel to convert a set of files from .xlsx to .csv automatically
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateScript({
if (Test-Path -Path (Resolve-Path $_) -PathType Container) { return $true }
else { throw "The SourcePath is not valid" }})]
[string]
$SourcePath,
[Parameter(Mandatory=$true)]
[ValidateScript({
if (Test-Path -Path (Resolve-Path $_) -PathType Container) { return $true }
else { throw "The DestinationPath is not valid" }})]
[string]
$DestinationPath,
[Parameter()]
[string]
$Filter = "*.xlsx"
)
begin {
# use this in the end block to ensure and Excel processes
# created by this script are closed, but others are left open
$existingExcelProcesses = Get-Process *excel* | ForEach-Object { $_.Id }
$excel = New-Object -COMObject Excel.Application;
}
process {
$SourcePath = Resolve-Path -Path $SourcePath
$DestinationPath = Resolve-Path -Path $DestinationPath
$csvFileName = @{l="CsvName";e={[System.IO.Path]::GetFileNameWithoutExtension($_.Name) + ".csv"}}
$csvFileType = 6
Get-ChildItem -Path $SourcePath -Filter $Filter | Select-Object Name,$csvFileName | ForEach-Object {
$excelPath = Join-Path -Path $SourcePath -ChildPath $_.Name -Resolve
$csvPath = Join-Path -Path $DestinationPath -ChildPath $_.CsvName
try {
$wb = $excel.Workbooks.Open($excelPath)
$wb.SaveAs($csvPath, $csvFileType)
$wb.Close(1) # close the document, forcing it to not ask to save
@{Name = $csvPath;Success=$true}
} catch {
Write-Error $_.Exception.Message
@{Name = $excelPath;Success=$false}
}
} | Select-Object Name,Success
}
end {
$excel.Quit()
# for some reason there was always an Excel Process hanging around
# that I thought $excel.Quit() would get rid of. I'm probably missing something...
Get-Process *excel* | Where-Object { -not ($existingExcelProcesses -contains $($_.Id) ) } | Stop-Process
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment