Reddit – Dive into anything
i am using the below script for uploading files to the FTP server it works but I have faced a problem when my script finds a file that has zero byte file size then it shows an exception. So how can I also upload a file that has zero byte file size?
#----------------------------------------------------------------
#Out Folder Path
$SearchOutPath = "C:\Orian\Out"
$CopytoOutHistory = "C:\Orian\Out\History"
#----------------------------------------------------------------
#Search only file from the C:\Orian\Out & select the file name & extension
$SearchfileOutfolder = Get-ChildItem -File $SearchOutPath
$FileName=$SearchfileOutfolder.Name
$FullPath="C:\Orian\Out\$FileName"
#Test-Path -Path C:\Orian\Out\$a -PathType Leaf
#If Files found - the script will transfer the files to a FTP server to a specified folder and also to c:\orian\out\history, and the files will be removed from original folder
if (Get-ChildItem -File $SearchOutPath -ErrorAction Ignore) {
try {
## checking file is foud or not if found then do orther wise break
if ((Test-Path -Path $FullPath -PathType Leaf -ErrorAction STOP)) {
#-------------connecting to ftp-------------
$username = "Shamim Reza"
$password = "admin"
$local_file = "$FullPath"
$remote_file = "ftp://192.168.0.105/ERP_Backup/$FileName"
#Creat FTP Request Object
$ftprequest = [System.Net.FtpWebRequest]::Create("$remote_file")
$ftprequest = [System.Net.FtpWebRequest]$ftprequest
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftprequest.Credentials = new-object System.Net.NetworkCredential($username, $password)
$ftprequest.UseBinary = $true
$ftprequest.UsePassive= $true
#Read the file for Upload
$filecontent = gc -en Byte $local_file
$ftprequest.ContentLength = $filecontent.Length
#Get Stream Request by bytes
$run = $ftprequest.GetRequestStream()
$run.Write($filecontent, 0, $filecontent.Length)
Start-Sleep -Seconds 2
#Cleanup
$run.Close()
$run.Dispose()
}
## Move the existing file to the Out\History folder.
Copy-Item -Path "$SearchOutPath\*.*" -Destination "$CopytoOutHistory" -recurse -Force -Verbose -ErrorAction STOP
## Remove the file in Out folder
Get-Childitem -File "$SearchOutPath\*.*" | Foreach-Object {Remove-Item $_.FullName} -ErrorAction STOP
} catch {
throw $_.Exception.Message
}
}
Exception
Exception calling "Write" with "3" argument(s): "Value cannot be null.
Parameter name: buffer"
At C:\Users\Shamim Reza\Desktop\Windows_10_update_Blocker\update1 frenzy ERP Backup
Script\Script_1_Upload_file_local_to_FTP.ps1:48 char:9
+ throw $_.Exception.Message
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Exception calli...r name: buffer":String) [], RuntimeException
+ FullyQualifiedErrorId : Exception calling "Write" with "3" argument(s): "Value cannot be null.
Parameter name: buffer"