PowerShell Scripts to Look for Excel files with .xls and .xlsx extensions - excel

I have an already written scripts which looks for ONLY an excel file with .xls extension. Now,
I want the same scripts to look for either .xls or .xlsx which ever it finds in that particular location and use it......
The old scripts search for files in the F column only on the excel sheet/file.....This makes the search takes forever, so I would like it to search the files in the F column which ONLY have this path:root_project/Fut_DB_Projects in the E column of the excel sheet.
Pls let me know exactly where to insert it in the scripts. I'm very new to Powershell and your answers would be very much appreciated.
# Creating an object for the Excel COM addin
$excelfile = $args[0]
$folder = $args[1]
echo $excelfile
echo $folder
if($excelfile -ne $Null -and $excelfile.Contains(".xls") -and (Test-Path $excelfile) -eq $True)
{
if($folder -ne $Null -And $folder.Contains("\") -and (Test-Path $folder) -eq $True)
{
$ExcelObject = New-Object -ComObject Excel.Application
# Opening the Workbook
$ExcelWorkbook = $ExcelObject.Workbooks.Open($excelfile)
# Opening the Worksheet by using the index (1 for the first worksheet)
$ExcelWorksheet = $ExcelWorkbook.Worksheets.Item(1)
#The folder where the files will be copied/The folder which will be zipped later
$a = Get-Date
$targetfolder = "C:\"+$a.Month+"_"+$a.Day+"_"+$a.Year+"_"+$a.Hour+$a.Minute+$a.Second
#Check if the folder already exists. Command Test-Path $targetfolder returns true or false.
if(Test-Path $targetfolder)
{
#delete the folder if it already exists. The following command deletes a particular directory
Remove-Item $targetfolder -Force -Recurse -ErrorAction SilentlyContinue
}
#The following command is used to create a particular directory
New-Item -ItemType directory -Path $targetfolder
echo "Temp folder created"
#Declaration of variables, COlumn value = 6 for Column F
$row = 1
$col = 6
# Read a value from the worksheet with the following command
$filename = $ExcelWorksheet.Cells.Item($row,$col).Value2
$filename
#change the folder value below to specify the folder where the powershell needs to search for the filename that it reads from excel file.
$null = ""
# Loop through each row in the excel file.
do
{
$filename = $ExcelWorksheet.Cells.Item($row,$col).Value2
#Checking if value read from Excel is Null
#In powershell operator for NOT EQUAL TO is -ne not <>
if($filename -ne $Null)
{
$filepath = $folder+$filename
#Check if the filepath read from excel is a real filepath OR check if the file exists.
if(Test-Path $filepath)
{
#If the file exists, move it to the folder declared above
# Change the below command to Move-Item if you want to Move the file and not Copy...
Copy-Item $filepath $targetfolder
}
else
{
#$Allfiles = Get-ChildItem -Recurse $folder
#You add the folders to the following list that you want the script to skip as it searches
#for the files through directory and its subdirectories
#eg. $xdir = #("Folder1","Folder2","Folder3")
$xdir = #("Tables","Views","Update","Synonyms","BES","ADTLTransit","Fut_DB_Jobs","Triggers","Scripts")
$remove = [string]::join("|",$xdir)
$Allfiles = Get-ChildItem -Recurse $folder | ? { $_.DirectoryName -notmatch $remove}
Write-Host -Fore Yellow ("Looking through subfolders now")
foreach ($file in $Allfiles)
{
$testpath = $file.FullName
if($testpath.Contains($filename))
{
Write-Host -Fore Yellow ("Found the file in a subfolder at location:" + $testpath)
Move-Item $testpath $targetfolder
}
}
}
}
#incrementing the row variable by 1 to move to the next available row in excel.
$row = $row + 1
}
#while condition evaluates if value read from the excel is null. If null, then the loop breaks.
while($filename -ne $Null)
# Important: The object needs to quit and the variables release, otherwise
# an Excel.exe will remain open.
$ExcelObject.Quit()
$ExcelObject = $null
$ExcelWorkbook = $null
$ExcelWorksheet = $null
[GC]::Collect()
do
{
}
while((Test-Path -path $targetfolder) -ne $True)
$targetfolderinfo = Get-ChildItem -Recurse $targetfolder | Measure-Object
$targetfolderfilecount = $targetfolderinfo.count
if($targetfolderfilecount -ne 0)
{
#Following command calls the function to zip all the files moved from source folder to target folder
$directory = [IO.DirectoryInfo] $targetfolder
If ($directory -eq $null)
{
Throw "Value cannot be null: directory"
}
Write-Host ("Creating zip file for folder (" + $directory.FullName + ")...")
[IO.DirectoryInfo] $parentDir = $directory.Parent
[string] $zipFileName
If ($parentDir.FullName.EndsWith("\") -eq $true)
{
# e.g. $parentDir = "C:\"
$zipFileName = $parentDir.FullName + $directory.Name + ".zip"
}
Else
{
$zipFileName = $parentDir.FullName + "\" + $directory.Name + ".zip"
}
If (Test-Path $zipFileName)
{
Remove-Item $zipFileName -Force -Recurse -ErrorAction SilentlyContinue
}
Set-Content $zipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
$shellApp = New-Object -ComObject Shell.Application
$zipFile = $shellApp.NameSpace($zipFileName)
If ($zipFile -eq $null)
{
Throw "Failed to get zip file object."
}
[int] $expectedCount = (Get-ChildItem $directory -Force -Recurse).Count
$expectedCount += 1 # account for the top-level folder
$zipFile.CopyHere($directory.FullName)
Write-Host -Fore Green ("Successfully created zip file for folder (" `
+ $directory.FullName + ").")
}
else
{
Write-Host -Fore Red ("There are no files to be zipped")
}
[System.Threading.Thread]::Sleep(10000)
Remove-Item $targetfolder -recurse
}
else
{
Write-Host -Fore Red ("Target folder path not specified correctly")
}
}
else
{
Write-Host -Fore Red ("Excel file path not specified")
}

Try changing the first if to this
if($excelfile -ne $Null -and $excelfile -like "*.xls*" -and (Test-Path $excelfile) -eq $True)

Related

Powershell script to search through a directory of excel files to find a string only searching through 1 file

I have found this script on https://shuaiber.medium.com/
I want to use it to find a certain string in a folder full of excel files.
the problem I am encountering is that it basically only searches through 1 file and then stops...
here is the script
Function Search-Excel {
[cmdletbinding()]
Param (
[parameter(Mandatory, ValueFromPipeline)]
[ValidateScript({
Try {
If (Test-Path -Path $_) {$True}
Else {Throw "$($_) is not a valid path!"}
}
Catch {
Throw $_
}
})]
[string]$Source,
[parameter(Mandatory)]
[string]$SearchText
#You can specify wildcard characters (*, ?)
)
$Excel = New-Object -ComObject Excel.Application
Try {
$Source = Convert-Path $Source
}
Catch {
Write-Warning "Unable locate full path of $($Source)"
BREAK
}
$Workbook = $Excel.Workbooks.Open($Source)
ForEach ($Worksheet in #($Workbook.Sheets)) {
$Found = $WorkSheet.Cells.Find($SearchText) #What
If ($Found) {
$BeginAddress = $Found.Address(0,0,1,1)
#Initial Found Cell
[pscustomobject]#{
WorkSheet = $Worksheet.Name
Column = $Found.Column
Row =$Found.Row
Text = $Found.Text
Address = $BeginAddress
}
Do {
$Found = $WorkSheet.Cells.FindNext($Found)
$Address = $Found.Address(0,0,1,1)
If ($Address -eq $BeginAddress) {
BREAK
}
[pscustomobject]#{
WorkSheet = $Worksheet.Name
Column = $Found.Column
Row =$Found.Row
Text = $Found.Text
Address = $Address
}
} Until ($False)
}
Else {
Write-Warning "[$($WorkSheet.Name)] Nothing Found!"
}
}
$workbook.close($false)
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$excel)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable excel -ErrorAction SilentlyContinue
}
And then I would use
Get-ChildItem -Path "C:\excelfiles" -Recurse -Include *.xls, *.xlsx, *.xlsm | Select-Object -Property Directory, Name | ForEach-Object { "{0}{1}" -f $.Directory, $.Name } | Search-Excel -SearchText MyText
I know its only searching through 1 file because I looked at another file and tried to get it to send me back to confirm yet it doesnt work.
Any help would be greatly appreciated.
You're going to need to include a loop within your function, or put the function within a ForEach-Object loop. For the function change you could do:
Function Search-Excel {
[cmdletbinding()]
Param (
[parameter(Mandatory, ValueFromPipeline)]
[ValidateScript({
Try {
If (Test-Path -Path $_) {$True}
Else {Throw "$($_) is not a valid path!"}
}
Catch {
Throw $_
}
})]
[string]$Source,
[parameter(Mandatory)]
[string]$SearchText
#You can specify wildcard characters (*, ?)
)
$Excel = New-Object -ComObject Excel.Application
ForEach($Path in $Source){
### <the rest of your existing code here, adjusted to work with $Path instead of $Source>
}
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$excel)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable excel -ErrorAction SilentlyContinue
}
Or, to work with your existing function you could just do:
Get-ChildItem -Path "C:\excelfiles" -Recurse -Include *.xls, *.xlsx, *.xlsm |
ForEach-Object { Search-Excel -Source $_.FullName -SearchText MyText }
So let's talk about a couple of things with your command.
Get-ChildItem -Path "C:\excelfiles" -Recurse -Include *.xls, *.xlsx, *.xlsm | Select-Object -Property Directory, Name | ForEach-Object { "{0}{1}" -f $.Directory, $.Name } | Search-Excel -SearchText MyText
If we break this up into the individual pieces (separated by pipes), we might be able to figure out what's wrong. The first part, Get-ChildItem, is only looking for files matching *.xls, *.xlsx, and *.xlsm, so already directories are excluded. Well, what exactly does this function return? If you were to look at the object types, you'll see System.IO.FileInfo, which has a bunch of properties built in. One of which is the full file path needed, .FullName.
Currently, Search-Excel is setup to only search one file. If you want to search multiple files at once, you'll need a loop somewhere. In my opinion, the easiest place to do that will be outside of the function, like this:
Get-ChildItem -Path "C:\excelfiles" -Recurse -Include *.xls, *.xlsx, *.xlsm | Foreach-Object { Search-Excel -Source $_.FullName -SearchText MyText }

Powershell Unable to find Excel and open Excel File

I am trying to have Powershell copy, rename than edit a excel file. It copies and renames the file as intended however when I go to open the file with excel it is unable to find the file. See attached code.
Thank you for the help.
#Export Textbox outputs
$S0 = $textBox1.Text
$jobname = $textBox2.Text
$contractor = $TextBox3.Text
#combine textbox outputs
$folder = "$S0" + "_" + "$jobname" + "_" + "$contractor"
$subsubfolder = ".\"+"$folder" + "\Dir"
$takeoffname = "$s0" + "_takeoff.xlsx"
#Excel
$xl = New-Object -ComObject excel.application
Start-Sleep -Seconds 5
$xl.Visible = $true
Start-Sleep -Seconds 5
$wb = $xl.Workbooks.Open("$subsubfolder\$takeoffname")
$data = $wb.Worksheets.Item("Storm")
$Data.Cells.Item(1,2) = "$jobname"
$data.Cells.Item(1,7) = "$S0"
$wb.Save()
$xl.Quit()
NEW updated Code - Added Join path and It broke the create folder loop. Sorry IF the added requirement to make the folder creates extra problems.
$S0 = $TextBox1.Text
$jobname = $TextBox2.Text
$contractor = $TextBox3.Text
$folder = ' {0}_{1}_{2}' -f $S0, $jobname, $Contractor
$file = '{0}_takeoff.xlsx' -f $S0
$PILname = 'PIL_{0}.xlsx' -f $S0
Write-host $folder
New-Item -ItemType Directory "./$folder"
foreach($line in Get-Content $Filenames)
{
New-Item $folder\$line -ItemType Directory
}
$subfolder = '{0}\1 - Estimating Original Quote Material' -f $folder
$subsubfolder = Join-Path -Path $PWD - ChildPath $Subfolder
$filePath = Join-Path -Path $PWD -ChildPath (Join-Path -Path $subsubfolderfolder -ChildPath $file)
$PILpath = Join-Path -Path $PWD -ChildPath (Join-Path -Path $subsubfolderfolder -ChildPath $PILname)
Write-host $filePath
Write-host $subsubfolder
pause
#Copy Files
Copy-Item '.\_master_takeoff.xlsx' "$subsubfolder\_master_takeoff.xlsx"
Copy-Item '.\PIL_S0XXXXX .xlsx' $subsubfolder
#Rename Files
Rename-Item -Path "$subsubfolder\_master_takeoff.xlsx" -newname $takeoffname
Rename-Item -Path "$subsubfolder\PIL_S0XXXXX .xlsx" -newname $PILpath
$xl = New-Object -ComObject excel.application
Start-Sleep -Seconds 5
$xl.Visible = $true
Start-Sleep -Seconds 5
$wb = $xl.Workbooks.Open("$subsubfolder\$takeoffname")
$data = $wb.Worksheets.Item("Storm")
$Data.Cells.Item(1,2) = "$jobname"
$data.Cells.Item(1,7) = "$S0"
$wb.Save()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
By taking strings off textboxes and combining that to a file path with string concatenation, you're bound to end up with a path that doesn't exist.
Having said that, the error comes from using the .\ in the path.
Powershell may know where that is, but Excel will have no idea where to look for the file. Excel has its own Default path, usually pointing to the Documents folder and when given relative paths, it will use that.
Always use existing, absolute file paths for opening stuff in external applications.
Better use something like this
#Export Textbox outputs
$prefix = $TextBox1.Text
$jobname = $TextBox2.Text
$contractor = $TextBox3.Text
#combine textbox outputs to form the directory (I like using the -f format operator)
$file = '{0}_takeoff.xlsx' -f $prefix
$folder = '{0}_(1}_{2}\Dir' -f $prefix, $jobname, $contractor
$filePath = Join-Path -Path $PWD -ChildPath (Join-Path -Path $folder -ChildPath $file)
# test if the file can be founc
if (Test-Path $filePath -PathType Leaf) {
$xl = New-Object -ComObject excel.application
$xl.Visible = $true
$wb = $xl.Workbooks.Open($filePath)
$data = $wb.Worksheets.Item("Storm")
$Data.Cells.Item(1,2) = $jobname
$data.Cells.Item(1,7) = $prefix
$wb.Save()
$xl.Quit()
# important: clean-up COM objects after use
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
else {
Write-Warning "File '$filePath' not found"
}
Instead of using $PWD (Print Working Directory) you can also use Get-Location which in fact is the same thing
Since I have no idea why your updated code is creating subfolders, I'll leave that out here.
Please look at how the -f Format operator works because now you're doing that wrong.
Also, to not confuse the working directory for PowerShell and the default path for Excel anymore, define the full root path first in the code. Below I'm using a variable called $workingDir for that.
Copy-Item can copy and rename at the same time.
# let's forget about the 'Set-Location' and use absolute paths from the beginning
$workingDir = '\\Server\Share\Folder' # set this to the real path
# Export Textbox outputs
$S0 = $TextBox1.Text
$jobname = $TextBox2.Text
$contractor = $TextBox3.Text
# combine textbox outputs to form the directory (I like using the -f format operator)
$PILname = 'PIL_{0}.xlsx' -f $S0
$file = '{0}_takeoff.xlsx' -f $S0
$folder = '{0}_(1}_{2}\1 - Estimating Original Quote Material' -f $S0, $jobname, $contractor
$folderPath = Join-Path -Path $workingDir -ChildPath $folder # --> Full absolute path to the working folder
$filePath = Join-Path -Path $folderPath -ChildPath $file # --> Full absolute path to the file
Write-host $filePath
Write-host $folderPath
#Copy and rename master Files
$masterFile = Join-Path -Path $workingDir -ChildPath '_master_takeoff.xlsx'
$pilFile = Join-Path -Path $workingDir -ChildPath 'PIL_S0XXXXX.xlsx'
Copy-Item -Path $masterFile -Destination $filePath
Copy-Item -Path $pilFile -Destination (Join-Path -Path $folderPath -ChildPath $PILname)
############################
#Write to new take off file
############################
# Call excel and open file
$xl = New-Object -ComObject excel.application
$xl.Visible = $true
$wb = $xl.Workbooks.Open($filePath)
$data = $wb.Worksheets.Item("Storm")
$Data.Cells.Item(1,2) = $jobname
$data.Cells.Item(1,7) = $S0
$wb.Save()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Everything seems ok with the code, but you are using relative paths.
If you are doing that, you need to change the working directory before opening the excel.
Ex: Set-Location C:\

Functions using multiple Foreach-Object

I have a part of my script that I can't get to work. The goal is, to take files from a folder, filter and organise them by an aspect of their filename, and move them to a new folder which has had new directories made for them. i.e organised by month and year based on file name. E.g. 032 Approved warranty - Croatia - Case-2019 08-1419032, goes into a directory 2019, then 08.
The next step was creating a select all function, which cycled through numbers 01-12. Which it does just fine. Now the issue is I want to cycle for each year as well between 2017-2019. Which is where i'm stuck.
This is my code which does work but only does all months and 1 selected year:
function DoWork { param ([int]$Month)
$StrMonth = $Month.ToString("00")
Echo $StrMonth.ToString("00")
$files = Get-ChildItem $destinationpath -Filter "*$group1 $StrMonth*" -Recurse
foreach ($file in $files)
{
$year = $group1.ToString()
$month = $Month.ToString()
$file.Name
$year
$StrMonth
# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $StrMonth
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
# Move File to new location
$file | move-Item -Destination $Directory -Force
}
}
if ($group -eq 'Select All') {
1..12 | ForEach-Object {DoWork($_)}
} else {
DoWork($group)
}
I want it too be able to repeat this for multiple years (Select All).
This code was suggested but doesn't work:
function DoWork {
Param([int]$Month,[int]$Year)
$StrMonth = $Month.ToString("00")
echo $StrMonth.ToString("00")
$StrYear = $Year.ToString
echo $StrYearToString
$files = Get-ChildItem $destinationpath -Filter "*$StrYear $StrMonth*" -Recurse
foreach ($file in $files) {
$year = $Year.ToString()
$month = $Month.ToString()
$file.Name
$StrYear
$StrMonth
# Set Directory Path
$Directory = $targetPath + "\" + $StrYear + "\" + $StrMonth
if (!(Test-Path $Directory)) {
New-Item $directory -Type Directory
}
$file | Copy-Item -Destination $Directory -Force
}
}
if ($group1 -eq 'Select All') {
2017..2019 | ForEach-Object {
$year = $_
1..12 | ForEach-Object {DoWork($_, $year)}
}
} elseif ($group -eq 'Select All') {
1..12 | ForEach-Object {DoWork($_, $group1)}
} else {
DoWork($group, $group1)
}
I have found that param block in your function is not correct, define param block as below:
Param([int]$Month,[int]$Year)

What is the reason for Powershell Excel SaveAs / Exception null-valued expression?

I'm working on a PowerShell script which unzips some .csv files, writes the contents inside an existing .xlsx file and saves this as a new .xlsx.
After some calculation I start a batch file from my PL/SQL code with DBMS.SCHEDULE. After the .bat file did some preparation it starts the PowerShell script.
I'm getting no error if I run the .bat file manually in a Windows command prompt window.
But I get an error while saving the .xlsx file if it is started from PL/SQL.
System.Management.Automation.RuntimeException You cannot call a method on a null-valued expression.
I tried to search in world wide web for a solution on this error but couldn't find one.
This is the line which produces the error message:
$WB.SaveAs($fileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2) | Out-Null
Here is the whole code:
#Unzip Files
function Unzip($file, $destination){
Expand-Archive $file -Destination $destination -Force
if (Test-Path $file) {
Remove-Item $file
}
}
#Add file to existing zip
function addZip($file, $destination){
Compress-Archive -Path $file -Update -DestinationPath $destination
}
#Write CSV into XLSX
function WriteFile($row, $column, $range){
foreach ($content in Get-Content $f.FullName) { #Get row
#If value not empty
if ($content) {
#Set value to cell
$WS.Cells.Item($row, $column) = $content
$colA = $ws.Range("$range$row")
$colrange = $ws.Range("$range$row")
#Split value by delimiter
#https://learn.microsoft.com/en-us/office/vba/api/excel.range.texttocolumns
$colA.TextToColumns($colrange, 1, -4142, $false, $false, $false, $false, $false, $true, "|") | Out-Null
$row = $row + 1
}
}
}
#Start
$XL = New-Object -ComObject Excel.Application
#Disable alerts
$XL.EnableEvents = $false
$XL.DisplayAlerts = $false
$XL.ScreenUpdating = $false
$param = $args[0].SubString(0, $args[0].IndexOf(".")) #Get name
$currentPath = Get-Location
$newPath = "$currentPath\$param\" #Temp new folder
#Create temp folder if exists
if (!(Test-Path $newPath)) {
New-Item -ItemType Directory -Force -Path $newPath
}
#Unzip
Unzip "$currentPath\$param.zip" $newPath
$files = Get-ChildItem -Path $newPath -Recurse #Get files
$XL.Workbooks.Open("$currentPath\test.xlsx")
$WB = $xl.ActiveWorkbook
$fileName = "$newPath"+"test_$param.xlsx"
#Loop through files
foreach ($f in $files) {
if ($f.Basename.ToUpper() -like "*A") {
$WS = $WB.Sheets.Item("A")
$WS.Activate() | Out-Null
WriteFile 10 1 "A" #Row / Column
addZip $f.FullName "$currentPath\$param.zip"
} elseif ($f.Basename.ToUpper() -like "*B") {
$WS = $WB.Sheets.Item("B")
$WS.Activate() | Out-Null
WriteFile 11 1 "A" #Row / Column
addZip $f.FullName "$currentPath\$param.zip"
} elseif ($f.Basename.ToUpper() -like "*C") {
$WS = $WB.Sheets.Item("C")
$WS.Activate() | Out-Null
WriteFile 12 1 "A" #Row / Column
addZip $f.FullName "$currentPath\$param.zip"
}
}
try {
#Delete File if exists
if ((Test-Path $fileName)) {
Remove-Item -Path $fileName -Recurse -Force -Confirm:$false
}
#Save
$WB.SaveAs($fileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2) | Out-Null
} catch {
New-Item "$currentPath\log.txt" -ItemType file
$_.Exception.GetType().FullName, $_.Exception.Message, $_.InvocationInfo.ScriptLineNumber |
Out-File "$currentPath\log.txt"
} finally {
#Close, Quit
$WB.Close($false) | Out-Null
$XL.Workbooks.Close()
$XL.Quit() | Out-Null
}
try {
addZip $fileName "$currentPath\$param.zip"
} catch {
New-Item "$currentPath\log1.txt" -ItemType file
$_.Exception.GetType().FullName, $_.Exception.Message, $_.InvocationInfo.ScriptLineNumber |
Out-File "$currentPath\log1.txt"
}
#Delete folder
if ((Test-Path $newPath)) {
Remove-Item -Path $newPath -Recurse -Force -Confirm:$false | Out-Null
}
#Release ComObject
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($XL)
spps -n Excel
This is the .bat file which runs the Powershell script:
powershell.exe -ExecutionPolicy RemoteSigned -File C:\Scripts\write_to_excel.ps1 %1
This is the PL/SQL code which runs the .bat file:
BEGIN
DBMS_SCHEDULER.create_job ('SCHEDULE_POWERSHELL',
job_action => 'c:\windows\system32\cmd.exe',
number_of_arguments => 4,
job_type => 'executable',
enabled => FALSE);
DBMS_SCHEDULER.set_job_argument_value ('SCHEDULE_POWERSHELL', 1, '/q');
DBMS_SCHEDULER.set_job_argument_value ('SCHEDULE_POWERSHELL', 2, '/c');
DBMS_SCHEDULER.set_job_argument_value ('SCHEDULE_POWERSHELL', 3, 'c:\Scripts\run_powershell.bat');
DBMS_SCHEDULER.set_job_argument_value ('SCHEDULE_POWERSHELL', 4, 'test_files.zip');
DBMS_SCHEDULER.enable ('SCHEDULE_POWERSHELL');
DBMS_SCHEDULER.run_job (job_name => 'SCHEDULE_POWERSHELL', use_current_session => TRUE);
EXCEPTION
WHEN OTHERS
THEN
log_trace_message ('SCHEDULE_POWERSHELL: ' || SQLERRM);
log_trace_message ('SCHEDULE_POWERSHELL: ' || DBMS_UTILITY.format_error_backtrace);
END;

Merging CSV Files into a XLSX with Tabs

I currently have 5 Registry CSV files which are created during a PowerShell script:
HKCC
HKCR
HKCU
HKLM
HKU
I need these CSV files to open at the end of the script however would like if all of them were contained within one XLSX file with 5 different headings
Is there a way to combine the files through PowerShell?
I understand how to get the data of the CSV files but don't understand how to merge them or convert. Some of the variables I believe which may be helpful.
$Date = Get-Date -Format "d.MMM.yyyy"
$DIR = $WPFlistview.Selecteditem.Ransomware
$path = "F:\Registry_Export\Results\$DIR\$Date\*"
$csvs = Get-ChildItem $path -Include *.csv
$output = "F:\Registry_Export\Results\$DIR\$Date\Results.Xlsx"
Paths to the CSV files if needed:
F:\Registry_Export\Results\$DIR\$Date\HKCR.CSV
F:\Registry_Export\Results\$DIR\$Date\HKCU.CSV
F:\Registry_Export\Results\$DIR\$Date\HKLM.CSV
F:\Registry_Export\Results\$DIR\$Date\HKU.CSV
F:\Registry_Export\Results\$DIR\$Date\HKCC.CSV
This is what I have tried prior. However, it completly scrambles my data into the wrong lines and cells:
function MergeCSV {
$Date = Get-Date -Format "d.MMM.yyyy"
$DIR = $WPFlistview.Selecteditem.Ransomware
$path = "F:\Registry_Export\Results\$DIR\$Date\*"
$csvs = Get-ChildItem $path -Include *.csv
$y = $csvs.Count
Write-Host "Detected the following CSV files: ($y)"
foreach ($csv in $csvs) {
Write-Host " "$csv.Name
}
$outputfilename = "Final Registry Results"
Write-Host Creating: $outputfilename
$excelapp = New-Object -ComObject Excel.Application
$excelapp.SheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
$sheet = 1
foreach ($csv in $csvs) {
$row = 1
$column = 1
$worksheet = $xlsx.Worksheets.Item($sheet)
$worksheet.Name = $csv.Name
$file = (Get-Content $csv)
foreach ($line in $file) {
$linecontents = $line -split ',(?!\s*\w+")'
foreach ($cell in $linecontents) {
$worksheet.Cells.Item($row,$column) = $cell
$column++
}
$column = 1
$row++
}
$sheet++
}
$output = "F:\Registry_Export\Results\$DIR\$Date\Results.Xlsx"
$xlsx.SaveAs($output)
$excelapp.Quit()
}
How the CSV looks
https://gyazo.com/177c7c3bb21ddf06d0ebacbb7f4d537b
How the XLSX looks
https://gyazo.com/cd5fb48d61f93aac5ec3034d81811094
So, using the Excel.Application ComObject still, what I would suggest is loading each CSV as a CSV, not using Get-Content like you are. Then use the ConvertTo-CSV cmdlet, specifying to use tab as the delimiter, and copy that to the clipboard. Then just paste into Excel, and it will paste in fairly nicely. You may want to adjust column size, but the data will show up just as you would expect it to. I would also use a For loop instead of a ForEach loop, since Excel plays nice with numbers for the tabs (though it is 1 based instead of PowerShell's 0 base). Here's what I would end up with after making those modifications:
function MergeCSV {
$Date = Get-Date -Format "d.MMM.yyyy"
$DIR = $WPFlistview.Selecteditem.Ransomware
$path = "F:\Registry_Export\Results\$DIR\$Date\*"
$csvs = Get-ChildItem $path -Include *.csv
$y = $csvs.Count
Write-Host "Detected the following CSV files: ($y)"
Write-Host " "$csvs.Name"`n"
$outputfilename = "Final Registry Results"
Write-Host Creating: $outputfilename
$excelapp = New-Object -ComObject Excel.Application
$excelapp.SheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
for($i=1;$i -le $y;$i++) {
$worksheet = $xlsx.Worksheets.Item($i)
$worksheet.Name = $csvs[$i-1].Name
$file = (Import-Csv $csvs[$i-1].FullName)
$file | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | Clip
$worksheet.Cells.Item(1).PasteSpecial()|out-null
}
$output = "F:\Registry_Export\Results\$DIR\$Date\Results.Xlsx"
$xlsx.SaveAs($output)
$excelapp.Quit()
}
You could use ImportExcel by Doug Finke And then replace your Export-CSV in the original script with Export-Excel -WorksheetName
Install-Module ImportExcel
Export-Excel "F:\Registry_Export\Results\$DIR\$Date\Results.xlsx" -worksheetname "HKCR"
Export-Excel "F:\Registry_Export\Results\$DIR\$Date\Results.xlsx" -worksheetname "HKCU"

Resources