Poweshell: force save of xlsm - powershell

First time here, hope the Community can help :-)
I tried the following with Powershell
it works well with an xlsx file
but it is KO with xlsm
EDIT:
I changed the code sequence below and force .DisplayAlert .
CSV files save are OK, but with console error.
Any idea for these errors ?
Console error
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Excel.DisplayAlerts = $false
$wb = $Excel.Workbooks.Open($fullpathExcelFile)
Start-Sleep -s 30
foreach ($ws in $wb.Worksheets) {
$Excel.DisplayAlerts = $false
$ws.SaveAs("$fullpathOutputdir\" + $ws.Name + ".csv", 6)
Write-Host "Save csv $ws.Name"
}
$Excel.DisplayAlerts = $false
$wb.Save()
$Excel.Quit()
Thanks !

Related

Issue with splitting Excel file (.xlxs) with Powershell based on column values

I have the below script that was posted here: Split Excelfile .xlxs with Powershell based on column values and it works as described but I am experiencing an issue.
The script will check one xlsx file and sort the content by unique values in column A and then copy these data set and create a new file.
The issue I am having is out of about 4000 files, 20 of them are created with the full data set from the original file. The rest of the files a split and created correctly. Not sure as to why this is occurring. Any help is appreciated.
Function Create-Excel-Spreadsheet {
Param($NameOfSpreadsheet)
# open excel
$excel = New-Object -ComObject excel.application
$excel.visible = $true
# add a worksheet
$workbook = $excel.Workbooks.Add()
$xl_wksht= $workbook.Worksheets.Item(1)
$xl_wksht.Name = $NameOfSpreadsheet
return $workbook
}
$objexcel = New-Object -ComObject Excel.Application
$wb = $objexcel.WorkBooks.Open("C:\Temp\Test.xlsx") # Changing path for test.xlsx file.
$objexcel.Visible = $true
$objexcel.DisplayAlerts = $False
$ws = $wb.Worksheets.Item(1)
$usedRange = $ws.UsedRange
$usedRange.AutoFilter()
$totalRows = $usedRange.Rows.Count
$rangeForUnique = $usedRange.Offset(1, 0).Resize($UsedRange.Rows.Count-1)
[string[]]$UniqueListOfRowValues = $rangeForUnique.Columns.Item(1).Value2 | sort -Unique
for ($i = 0; $i -lt $UniqueListOfRowValues.Count; $i++) {
$newRange = $usedRange.AutoFilter(1, $UniqueListOfRowValues[$i])
$workbook = Create-Excel-Spreadsheet $UniqueListOfRowValues[$i]
$wksheet = $workbook.Worksheets.Item(1)
$range = $ws.UsedRange.Cells
$range.Copy()
$wksheet.Paste($wksheet.Range("A1"))
$workbook.SaveAs("C:\temp\" + $UniqueListOfRowValues[$i], $xlFixedFormat)
$workbook.Close()
}

How can i idelete sheet in excel file using powershell?

This is my code, below:
# Specify the path to the Excel file and the WorkSheet Name
$FilePath = "C:\Downloads\Portalroom_CW30.xlsx"
$SheetName = "4_docexchange"
# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
# Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet 'BuildSpecs'
$WorkSheet = $WorkBook.sheets.item($SheetName)
$WorkBook.close($true)
$objExcel.Quit()
Please help me resolv, Thanks !!
You can call the Delete() method on your worksheet in order to do so. But before that you would want to set DisplayAlerts option as $false and would save the $Workbook after you are done deleting. Your code will look like this -
#Specify the path to the Excel file and the WorkSheet Name
$FilePath = "C:\Downloads\Portalroom_CW30.xlsx"
$SheetName = "4_docexchange"
#Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
#Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false
#Set Display alerts as false
$objExcel.displayalerts = $False
#Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
#Load the WorkSheet 'BuildSpecs'
$WorkSheet = $WorkBook.sheets.item($SheetName)
#Deleting the worksheet
$WorkSheet.Delete()
#Saving the worksheet
$WorkBook.Save()
$WorkBook.close($true)
$objExcel.Quit()

How to Remove Duplicate rows in Excel from Powershell?

I have the following code:
$xl = New-Object -comobject Excel.Application
$xl.visible = $true
$wb = $xl.Workbooks.Add("D:temp\test.xls")
$ws = $wb.worksheets.item(1)
$Range = $ws.range("J6:J65000")
$Range.Removeduplicates()
[gc]::collect()
[gc]::WaitForPendingFinalizers()
$xl.workbooks.close()
$xl.application.quit()
Comes back with "doesn't contain a method named 'RemoveDuplicates'
All i want to do is delete the row if a duplicate value in column J is found.
The data in column J is a long string (20 characters) of letters and numbers and some symbols like "#,=;-"
Can anyone help me?
it would be useful for someone, this works for me in office 365 pro plus version 1703 and powershell v5:
$path = 'C:\Users\john\Desktop\rows.xlsx'
$Excel = New-Object -ComObject excel.application
$Excel.visible = $True
$Excel.DisplayAlerts = $False
$Workbook = $excel.Workbooks.open($path)
$WS = $Workbook.WorkSheets.Add()
$Worksheet = $Workbook.WorkSheets.item('Sheet1')
$worksheet.activate()
$Range = $Worksheet.Range('A2:G154')
$Range.Copy() | Out-null
$Worksheet = $Workbook.WorkSheets.item('Sheet2')
$Range = $Worksheet.Range('A2:G154')
$Range.PasteSpecial(-4104)
$Range = $Worksheet.Range('A2:G154')
$Worksheet.UsedRange.RemoveDuplicates(1)
$workbook.Save()
$Excel.Quit()
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Workbook)
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Worksheet)
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Range)
BR!!

Remove "sharing" from Excel workbook

I'm trying to save a workbook to a new location with a password and keep the filename the same. The filname gets updated weekly with a date appended to it, so it's never the same. There are two things I'm having trouble with:
Using the SaveAs method to save the file with the same name in a different path &
I can't add a password because the workbook is shared.
I'm scripting this out in PowerShell, and if possible, I'd like to unshare the workbook in the script. Unfortunately, I can't seem to find a method that accomplishes this. Here is what I have so far... I really appreciate any advice.
$xls = new-object -com excel.application
$xls.Visible = $False
$xlsWB = $xls.Workbooks.Open("path\*.xlsx")
$xlsWB.Password = "Password"
$xlsWB.SaveAs("differentPath\*.xlsx")
$xls.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xls)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWB)
Turns out, there is a method that can be called to change the sharing status of the workbook. It's ExclusiveAccess().
Here is my working code that solved the problem:
$xls = new-object -comObject excel.application
$xls.Visible = $False
$xls.DisplayAlerts = $False
$xlsWB = $xls.Workbooks.Open("FilePath")
$xlsWB.ExclusiveAccess()
$xlsWB.Password = "AddThisPassword"
$xlsWB.Save()
$xlsWB.Close()
$xls.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xls)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWB)
move "CurrentPath" "NewPath"
Once I change the sharing status of the workbook, the Password method successfully adds a password to the workbook, solving the second issue described in the OP. Rather than use SaveAs(), I decided to simply move the file, which saves me from deleting the source file.
Thanks and I hope someone finds this useful.
this was my attempt at a similar problem. It removes the MultiUserEditing of files within a folder structure.
foreach ($file in (Get-ChildItem "C:\path_to_reports\" -File -Filter "*.xls" -recurse))
{
#The filter seems to also work for *.xlxsx
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $False
$Excel.DisplayAlerts = $False
$ExcelWorkbook = $Excel.workbooks.open($file.fullname)
If ($ExcelWorkbook.MultiUserEditing -eq "True")
{
$ExcelWorkbook.ExclusiveAccess()
$ExcelWorkbook.Save()
}
#close the workbook and not the file
$ExcelWorkbook.Close()
#Quit the file
$Excel.Quit()
#cleanup
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
#more clean up
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelWorkbook)
#the most clean up
Remove-Variable -Name excel
}

How to Open; SaveAs; then Close an Excel 2013 (macro-enabled) workbook from PowerShell4

Doing a search on the above Com operations yields links dating to '09 and even earlier. Perhaps it hasn't changed but I find myself bumping up against errors where 'it is being used by another process.' - even though no Excel app is open on my desktop. I have to reboot to resume.
To be clear - I'm trying to open an existing file; immediately SaveAs() (that much works), add a sheet, Save(); Close() - and then, importantly, repeat that cycle. In effect, I'm creating a few dozen new sheets within a loop that executes the above 'Open Master; SaveAs(); Edit Stuff; Save; Close;
From the examples I've seen this is not a typical workflow for PowerShell. Pasted at the very bottom is my provisional script - pretty rough and incomplete but things are opening what they need to open and adding sheet also works - until I know I have the right way to cleanly close stuff out I'm not worried about the iterations.
I've found a couple examples that address closing:
From http://theolddogscriptingblog.wordpress.com/2012/06/07/get-rid-of-the-excel-com-object-once-and-for-all/
$x = New-Object -com Excel.Application
$x.Visible = $True
Start-Sleep 5
$x.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($x)
Remove-Variable x
And from http://social.technet.microsoft.com/Forums/windowsserver/en-US/24e57b61-e792-40c1-8aff-b0a8205f48ab/updated-opened-excel-using-powershell?forum=winserverpowershell
Set-ItemProperty $path -name IsReadOnly -value $false
$Excel.ActiveWorkBook.Save()
$openfile.Close()
$openfile = $null
$Excel.Quit()
$Excel = $null
[GC]::Collect()
<>
function MakeNewBook($theWeek, $AffID){
$ExcelFile = "C:\csv\InvoiceTemplate.xlsm"
$Excel = New-Object -Com Excel.Application
$Excel.Visible = $True
$Workbook = $Excel.Workbooks.Open($ExcelFile)
$theWeek = $theWeek -replace "C:\\csv\\", ""
$theWeek = $theWeek -replace "\.csv", ""
$theWeek = "c:\csv\Invoices\" +$AffID +"_" + $theWeek + ".xlsm"
$SummaryWorksheet = $Workbook.worksheets.Item(1)
$Workbook.SaveAs($theWeek)
return $Excel
}
function MakeNewSheet($myBook, $ClassID){
$SheetName = "w"+$ClassID
#$Excel = New-Object -Com Excel.Application
#$Excel.Visible = $True
$wSheet = $myBook.WorkSheets.Add()
}
function SaveSheet ($myExcel)
{
#$WorkBook.EntireColumn.AutoFit()
#Set-ItemProperty $path -name IsReadOnly -value $false
$myExcel.ActiveWorkBook.Save()
$openfile= $myExcel.ActiveWorkBook
$openfile.Close()
$openfile = $null
$myExcel.Quit()
$myExcel = $null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($myExcel)
Remove-Variable $myExcel
[GC]::Collect()
}
$theWeek = "C:\csv\wkStart2013-11-04.csv"
$x = Import-Csv $theWeek
foreach ($xLine in $x){
if ($x[0]){
$AffID = $x[1].idAffiliate
$myExcel = MakeNewBook $theWeek $x[1].idAffiliate
$ClassID = $x[1].idClass
MakeNewSheet $myExcel $ClassID
continue
}
SaveSheet($myExcel)
$AffID = $_.$AffID
$wID = $xLine.idClass
#MakeNewSheet($wID)
Echo "$wID"
}
As a follow up after playing around with this issue myself. I geared my solution around Ron Thompson's comment minus the function calls:
# collect excel process ids before and after new excel background process is started
$priorExcelProcesses = Get-Process -name "*Excel*" | % { $_.Id }
$Excel = New-Object -ComObject Excel.Application
$postExcelProcesses = Get-Process -name "*Excel*" | % { $_.Id }
# your code here (probably looping through the Excel document in some way
# try to gently quit
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
# otherwise allow stop-process to clean up
$postExcelProcesses | ? { $priorExcelProcesses -eq $null -or $priorExcelProcesses -notcontains $_ } | % { Stop-Process -Id $_ }
My experience has been that the Quit method doesn't work well, especially when looping. When you get the error, instead of rebooting, open up Task Manager and look at the Processes tab. I'm willing to bet you'll see Excel still open -- maybe even multiple instances of it. I solved this problem by using Get-Process to find all instances of Excel and piping them to Stop-Process. Doesn't seem like that should be necessary, but it did the trick for me.
You should not have to keep track of processes and kill them off.
My experience has been that to properly and completely close Excel (including in loops), you also need to release COM references. In my own testing have found removing the variable for Excel also ensures no remaining references exist which will keep Excel.exe open (like if you are debugging in the ISE).
Without performing the above, if you look in Task Manager, you may see Excel still running...in some cases, many copies.
This has to do with how the COM object is wrapped in a “runtime callable wrapper".
Here is the skeleton code that should be used:
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook = $excel.Workbooks.Add()
# or $workbook = $excel.Workbooks.Open($xlsxPath)
# do work with Excel...
$workbook.SaveAs($xlsxPath)
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
# no $ needed on variable name in Remove-Variable call
Remove-Variable excel
Try this
$filePath = "E:\TSMBackup\TSMDATAPull\ODCLXTSM01_VM.xlsx"
$excelObj = New-Object -ComObject Excel.Application
$excelObj.Visible = $true
$workBook = $excelObj.Workbooks.Open($filePath)
$workSheet = $workBook.Sheets.Item("Sheet1")
$workSheet.Select()
$workBook.RefreshAll()
$workBook.Save()
$excelObj.Quit()