Convert Excel formats to pdf - Powershell - powershell

My question's about the error at saving file at this convert script:
https://github.com/idf/batch_dump/blob/master/office_convert.ps1
#Error
Exception when calling "InvokeMember" with "6" argument (s): "Object does not match destination type."
In the line: 28 character: 1
+ $workbook = $objExcel.Workbooks.PSBase.GetType().InvokeMember('Open', ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : TargetException
saving C:\Test\CD_FEV_1.pdf
You can not call a method on a null value expression.
In the line: 30 character: 1
+ $workbook.ExportAsFixedFormat($xlTypePDF, $filepath, $xlQualityStanda ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You can not call a method on a null value expression.
In the line: 31 character: 1
+ [void]$workbook.PSBase.GetType().InvokeMember('Close', [Reflection.Bi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
As i haven't experience in powershell i don't understand the metod they call at script.

I'm still new to powershell myself, so can't answer specifically what was causing the error, however I think I found the solution. It seemed to be with only the Excel conversion. The Word and PPT conversions worked flawless. I've changed the code for that portion and it seems to be working now:
$folderpath = $(get-location)
Add-type -AssemblyName office
#Convert Word formats to pdf
$wdFormatPDF = 17
$word = New-Object -ComObject word.application
$word.visible = $false
$fileTypes = "*.docx","*doc"
$wordFiles = Get-ChildItem -path $folderpath -include $fileTypes -Recurse
foreach ($d in $wordFiles) {
$path = ($d.fullname).substring(0,($d.FullName).lastindexOf("."))
"Converting $path to pdf ..."
$doc = $word.documents.open($d.fullname)
$doc.saveas([ref] $path, [ref]$wdFormatPDF)
$doc.close()
}
$word.Quit()
#Convert Excel formats to pdf
$xlFixedFormat = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$excelFiles = Get-ChildItem -Path $folderpath -include *.xls, *.xlsx -recurse
$objExcel = New-Object -ComObject excel.application
$objExcel.visible = $false
foreach($wb in $excelFiles)
{
$filepath = Join-Path -Path $folderpath -ChildPath ($wb.BaseName + ".pdf")
$workbook = $objExcel.workbooks.open($wb.fullname, 3)
$workbook.ActiveSheet.PageSetup.Orientation = 2
$objExcel.PrintCommunication = $false
$workbook.ActiveSheet.PageSetup.FitToPagesTall = $false
$workbook.ActiveSheet.PageSetup.FitToPagesWide = 1
$objExcel.PrintCommunication = $true
$workbook.Saved = $true
"saving $filepath"
$workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $filepath)
$objExcel.Workbooks.close()
}
$objExcel.Quit()
#Convert Powerpoint formats to pdf
$ppFormatPDF = 2
$ppQualityStandard = 0
$p = new-object -comobject powerpoint.application
$p.visible = [Microsoft.Office.Core.MsoTriState]::msoTrue
$ppFiletypes = "*.pptx","*ppt"
$ppFiles = Get-ChildItem -path $folderpath -include $ppFiletypes -Recurse
foreach ($s in $ppFiles) {
$pppath = ($s.fullname).substring(0,($s.FullName).lastindexOf("."))
"Converting $pppath to pdf ..."
$ppt = $p.presentations.open($s.fullname)
$ppt.SavecopyAs($pppath, 32) # 32 is for PDF
$ppt.close()
}
$p.Quit()
$p = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()

Related

Change Last Writing Date using date in file name

I would like to change the Last writing date of several CSV files using the dates contained in the names of the different files
Example :
Input : File_20221210085032.CSV (LastWriteTime = 25 October 2022 16:54:25)
Output :(LastWriteTime = 10 December 2022 08:50:32)
In that extent i wrote a code based on my knowledge and some help from internet, this code should do what i want to achieve however i get some errors and i cannot find the errors.
Please find below my code :
cls
$Foldober = 'D:\Bob\Test'
$DateFormat = "yyyymmddhhmmss"
$FileList = Get-ChildItem -LiteralPath $Folder -Filter '*.csv' -File
foreach ($FL_Item in $FileList) {
$Null = $FL_Item.BaseName -match '_\d{14}'
$DateString = $Matches.DateString
$date_from_file = [datetime]::ParseExact($DateString, $DateFormat, $Null)
$FL_Item.CreationTime = $date_from_file
$FL_Item.LastWriteTime = $date_from_file
$FL_Item.LastAccessTime = $date_from_file
# show the resulting datetime info
'=' * 20
$CurrentFileInfo = Get-Item -LiteralPath $FL_Item.FullName
$CurrentFileInfo.FullName
$CurrentFileInfo.CreationTime
$CurrentFileInfo.LastWriteTime
$CurrentFileInfo.LastAccessTime
}
I get the following error
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At C:\Users\Bob\Desktop\Script\test.ps1:15 char:5
+ $date_from_file = [datetime]::ParseExact($DateString, $DateFormat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
Update #2
After having got ridden of $null in the ParsExact as suggested i get the following errors :
cls
$Foldober = 'D:\Bob\Test'
$DateFormat = "yyyymmddhhmmss"
$FileList = Get-ChildItem -LiteralPath $Folder -Filter '*.csv' -File
foreach ($FL_Item in $FileList) {
$Null = $FL_Item.BaseName -match '_\d{14}'
$DateString = $Matches.DateString
$date_from_file = [datetime]::ParseExact($DateString, $DateFormat)
$FL_Item.CreationTime = $date_from_file
$FL_Item.LastWriteTime = $date_from_file
$FL_Item.LastAccessTime = $date_from_file
# show the resulting datetime info
'=' * 20
$CurrentFileInfo = Get-Item -LiteralPath $FL_Item.FullName
$CurrentFileInfo.FullName
$CurrentFileInfo.CreationTime
$CurrentFileInfo.LastWriteTime
$CurrentFileInfo.LastAccessTime
}
Cannot find an overload for "ParseExact" and the argument count: "2".
At C:\Users\Bob\Desktop\Script\test.ps1:15 char:5
+ $date_from_file = [datetime]::ParseExact($DateString, $DateFormat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception setting "CreationTime": "Cannot convert null to type "System.DateTime"."
At C:\Users\Bob\Desktop\Script\test.ps1:17 char:5
+ $FL_Item.CreationTime = $date_from_file
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Thanks in advance for your help. Best regards

Uploading 2 files with same name to FTP using powershell script

I am a beginner at powershell script and I am stuck
I am trying to upload 2 xml files with the same name to FTP, but I am getting the following error
Exception calling "UploadFile" with "2" argument(s): "An
exception occurred during a WebClient request." At
C:\powershell\ExternalWidgets\upload-to-ftp.ps1:51 char:16
+ $webclient.UploadFile($uri.AbsoluteUri, $LocalPath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException`
Here is the script:
#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)
cd $target
$DirectoryContent = Get-ChildItem -Directory
foreach($item in $DirectoryContent){
cd $item
$currentFolderItems = Get-ChildItem
foreach( $subfolderItem in $currentFolderItems)
{
if ($subfolderItem.name -eq "package.json") {
$subItem = Get-ChildItem -Directory
foreach($subItem in $subItem)
{
if ($subItem.name -eq "coverage") {
$files = Get-ChildItem -Path $subItem
$n = 0
foreach ($file in $files)
{
#rename coverage file
if($file.Name -eq "cobertura-coverage.xml") {
$newFileName=$file.Name.Replace("cobertura-coverage.xml","cobertura-coverage$n.xml")
Rename-Item $file -NewName $newFileName
$newFileName
}
$n++
}
}
}
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object
System.Net.NetworkCredential($user,$pass)
$uri = New-Object System.Uri($ftp + "/" + $folder)
#Delete files from FTP
# $fileUploaded =($uri + "\" + $newFileName)
# $fileUploaded
# Remove-Item $fileUploaded
$LocalPath =($target + "\" + $item + "\" + "coverage" + "\" +
$newFileName).Replace(".\", "").Replace('\', '/')
$webclient.UploadFile($uri, $LocalPath)
#cd..
}
}
cd ..
}
I also get an error when I want to rename one of the files. What step am I missing? Thank you

Powershell script errors first time but works on second attempt

I have a powershell script that searches for xls files and converts them to xlsx. Every time I run it for the first time I will get the error
Unable to find type [Microsoft.Office.Interop.Excel.XlFileFormat].
At C:\Users\wpauling\Documents\Quarter Report Scripts\convert.ps1:2 char:18
+ ... xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpen ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Offic...el.XlFileFormat:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
However the second time I run it everything works as expected, what is the problem I am going nuts. Here is my script
#Converts xls into xlsx
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $false
$folderpath = "C:\Users\user1\Documents\Q4"
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype -recurse |
ForEach-Object `
{
$path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
"Converting $path"
$workbook = $excel.workbooks.open($_.fullname)
$path += ".xlsx"
$workbook.saveas($path, $xlFixedFormat)
$workbook.close()
remove-item $_.fullname
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
Start the script with the line
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
Hope that helps.
p.s. Much less descriptive of course, but you can also use the numeric enum value 51 for the variable and not use the Add-Type.
See: XlFileFormat enumeration

Extracting attachments from SharePoint online using PowerShell

Currently I am trying to extract attachments from a list on SharePoint online. I found a code online that is supposed to do this but i get an error. The code that I found is a follows:
$webUrl = "https://mm.sharepoint.com/teams/pj-b0000"
$library = "Photos"
#Local Folder to dump files
$tempLocation = "C:\Users\C\Documents\temp"
$s = new-object Microsoft.SharePoint.SPSite($webUrl)
$w = $s.OpenWeb()
$l = $w.Lists[$library]
foreach ($listItem in $l.Items)
{
Write-Host " Content: " $listItem.ID
$destinationfolder = $tempLocation + "\" + $listItem.ID
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
foreach ($attachment in $listItem.Attachments)
{
$file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)
$bytes = $file.OpenBinary()
$path = $destinationfolder + "\" + $attachment
Write "Saving $path"
$fs = new-object System.IO.FileStream($path, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
}
}
but i get this error:
new-object : Cannot find type [Microsoft.SharePoint.SPSite]: verify that the assembly containing this type is loaded.
At C:\Users\C\Documents\SPListExtract.ps1:5 char:6
+ $s = new-object Microsoft.SharePoint.SPSite($webUrl)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Users\C\Documents\SPListExtract.ps1:6 char:1
+ $w = $s.OpenWeb()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot index into a null array.
At C:\Users\C\Documents\SPListExtract.ps1:7 char:1
+ $l = $w.Lists[$library]
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
so i edited that code a bit but i only get the item in the list and not the attachments that are in the items. The code that i wrote is as follows:
Connect-PnPOnline -Url 'https://mm.sharepoint.com/teams/pj-b0000' -UseWebLogin
$tempLocation = "C:\Users\C\Documents\temp"
$list = Get-PnPListItem -List 'Photos'
foreach ($listItem in $list)
{
Write-Host " Content: " $listItem.ID
$destinationfolder = $tempLocation + "\" + $listItem.ID
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
foreach ($attachment in $listItem.Attachments)
{
$file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)
$bytes = $file.OpenBinary()
$path = $destinationfolder + "\" + $attachment
Write "Saving $path"
$fs = new-object System.IO.FileStream($path, "OpenOrCreate")
$fs.Write($bytes, 0 , $bytes.Length)
$fs.Close()
}
}
I see my problem is the inside foreach loop for the $file variable I think. Would someone be able to help me with this?
Much thanks in advance.
The first line in your errors implies you do not have the assembly loaded:
new-object : Cannot find type [Microsoft.SharePoint.SPSite]: verify that the assembly containing this type is loaded.
These assemblies are only installed on a SharePoint server:
https://social.technet.microsoft.com/Forums/en-US/4a78ed2c-efde-40fa-800c-c4ecfa68a7c4/cannot-find-type-microsoftsharepointspsite-when-running-sharepoint-powerscript-in-a-windows-10?forum=sharepointdevelopment

Extract Data from .txt files and export it to a .csv file #powershell

I am a beginner in Powershell, and I need some help. Thanks in advance
Requirement:
Get files inside a folder by browsing with a Folderbrowser.
Get the data inside the different .txt files.
Paste it into a single sheet of a .csv table.
Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
[void]$FolderBrowser.ShowDialog()
$Selection = $FolderBrowser.SelectedPath
$input = Get-ChildItem $Selection
$objects = ForEach($record in $data)
{
$props = #{}
foreach($input in $Selection)
{
$records +=Get-Content $data
$props.Add($records)
}
}
$AllFilesData = New-Object -TypeName PSObject -Property $props
$path = $Selection+"\"+"AllFilesTogether.csv"
$objects | Select-Object AllFilesData| Export-Csv -NoTypeInformation -Path $path
Error:
Get-Content : Cannot find path
'D:\users\F14897c\sd_conex_france_20170107002029.txt' because it does
not exist.
At line:14 char:15
+ $records +=Get-Content $data
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (D:\users\F14897...70107002029.txt:String) [Get-Content],
ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand Cannot
find an overload for "Add" and the argument count: "1".
At line:16
char:9
+ $props.Add($records)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
A single-column CSV file is just a list of strings, so your script can be simplified immensely:
Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
[void]$FolderBrowser.ShowDialog()
$Selection = $FolderBrowser.SelectedPath
Get-ChildItem $Selection -Filter *.txt |Get-Content |Out-File (Join-Path $Selection AllFilesTogether.csv)
You obviously aren't giving the whole code, as $data in the ForEach loop is never defined. Regardless, the reason why you are getting the errors is that you need to change:
$records +=Get-Content $data
to
$records +=Get-Content $data.FullName
Assuming that $data is the result of a Get-ChildItem.
Also, you are trying to add to a hash table with 1 argument, which isn't going to fly either. You will need to supply a key value pair. If you are only going to use one column, then declare an array with #() instead of a Hash table.