Uploading 2 files with same name to FTP using powershell script - powershell

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

Related

Powershell - Saving downloaded file on network share

The PS1 needs to download an XML file from a remote HTTP server and save it on a network share.
Summary of the script is as follows
$timer = (Get-Date -Format yyyyMMdd_hhmmss)
$storageDir = "\\10.16.99.99\what\ever\Folder"
$filename1 = "John_" + "$timer.xml"
$webclient = New-Object System.Net.WebClient
$url1 = "http://whateverURL/John.xml"
$file1 = "$storageDir\$filename1"
$webclient.DownloadFile($url1,$file1)
$source = "\\10.16.99.99\what\ever\Folder"
$target = "\\10.16.99.99\what\ever\TargetFolder"
$files = get-childitem $source -Recurse
foreach ($file in $files){
if ($file.LastWriteTime -ge (get-date).AddMinutes(-10)){
$targetFile = $target + $file.FullName.SubString($source.Length)
New-Item -ItemType File -Path $targetFile -Force
Copy-Item $file.FullName -destination $targetFile
Start-Sleep -s 3
}
}
When I run the script, I get following error through PowerShell CMD
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient
request."
At D:\StagisEE\GlobalListing\GL_download.ps1:318 char:3
+ $webclient.DownloadFile($url1,$file1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Therefore I added the following lines to see what the variables are that will be used in the webClient command
Write-Host $url1
Write-Host $file1
Which gave me the following, additional, results
http://whateverURL/John.xml
\\10.16.99.99\what\ever\Folder\John_20191224_103412.xml
My question is why that the webClient is failing while the variables seems to be ok?
Or is he struggling due to the network location?

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

Convert Excel formats to pdf - 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()

I want to extract all .zip files in a given directory in temp using powershell

I wrote the following code for extracting the .zip files to temp:
function Expand-ZIPFile($file, $destination)
{
$shell = new-object -com shell.application
$zip = $shell.NameSpace($file)
foreach ($item in $zip.items()) {
$shell.Namespace($destination).copyhere($item)
}
}
Expand-ZIPFile -file "*.zip" -destination "C:\temp\CAP"
But I got the following error:
PS C:\Users\v-kamoti\Desktop\CAP> function Expand-ZIPFile($file, $destination)
{
$shell = new-object -com shell.application
$zip = $shell.NameSpace($file)
foreach ($item in $zip.items()) {
$shell.Namespace($destination).copyhere($item)
}
}
Expand-ZIPFile -file "*.zip" -destination "C:\temp\CAP"
You cannot call a method on a null-valued expression.
At line:5 char:19
+ foreach($item in $zip.items())
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
Get-ChildItem 'path to folder' -Filter *.zip | Expand-Archive -DestinationPath 'path to extract' -Force
requires ps v5
You can use this if you want to create a new folder for each zip file:
#input variables
$zipInputFolder = 'C:\Users\Temp\Desktop\Temp'
$zipOutPutFolder = 'C:\Users\Temp\Desktop\Temp\Unpack'
#start
$zipFiles = Get-ChildItem $zipInputFolder -Filter *.zip
foreach ($zipFile in $zipFiles) {
$zipOutPutFolderExtended = $zipOutPutFolder + "\" + $zipFile.BaseName
Expand-Archive -Path $zipFile.FullName -DestinationPath $zipOutPutFolderExtended
}
You have to provide the full path explicitly (without wildcards) in the following call:
$shell.NameSpace($file)
You could rewrite your function like this:
function Expand-ZIPFile($file, $destination)
{
$files = (Get-ChildItem $file).FullName
$shell = new-object -com shell.application
$files | %{
$zip = $shell.NameSpace($_)
foreach ($item in $zip.items()) {
$shell.Namespace($destination).copyhere($item)
}
}
}

Close a file handle opened by .NET

I'm working on a script to rename files based on EXIF data.
param([string]$path)
# http://blogs.technet.com/b/jamesone/archive/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course.aspx
[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") | out-null
function MakeString {
$s=""
for ($i=0 ; $i -le $args[0].value.length; $i ++) {
$s = $s + [char]$args[0].value[$i]
}
return $s
}
$files = Get-ChildItem -Path $path
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
$exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
$captureDate = MakeString $exif.GetPropertyItem(36867)
$captureDate = ($captureDate -replace ":", '-').Substring(0,19)
$newFilename = $captureDate + " " + $file.Name.Trim()
$file.Name + " -> " + $newFilename
$file |Rename-Item -NewName $newFilename
}
Reading the date from EXIF is no problem, but when I try to rename the file I get this error message:
Rename-Item : The process cannot access the file because it is being used by another process.
At D:\Norwegen\RenamePhotos.ps1:25 char:12
+ $file |Rename-Item -NewName $newFilename
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:\Norwegen\P1270465 (1920x1433).jpg:String) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
When I monitor the directory in ProcMon I can see that the files are closed rather late:
(look at the highlighted line, it's from an earlier file in the middle of the entries from the file currently being processed)
So, how can I close the file (which is probably still open from the EXIF read) so I can rename it?
What I already tried to close the open file:
Remove-Variable exif
$file.Close()
Since you only read from the the file, then a call to Dispose() should do the trick. Ex.
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
$exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
$captureDate = MakeString $exif.GetPropertyItem(36867)
#Disposing object as soon as possible
$exif.Dispose()
$captureDate = ($captureDate -replace ":", '-').Substring(0,19)
$newFilename = $captureDate + " " + $file.Name.Trim()
$file.Name + " -> " + $newFilename
$file |Rename-Item -NewName $newFilename
}