Powershell error

chetan Vishwakarma 146 Reputation points
2022-02-02T07:05:44.803+00:00

Hello ,
I have developed the code for transferring the file to FTP server and send notification and the script is working fine in my local system but if i am executing the same script on server it is throwing error:

$SFTPServer = "test.ftp.com"  
$SFTPUser = "user"  
$Pass = "password"  
$SourceFilelocation = "\\SourceServer\Script\FTPTest\Output_Files\"  
$BakupFileLocation = "\\SourceServer\Script\FTPTest\Backups\"  
$RemoteLocation = "//destinationDirectory/"  
$todaysdate=Get-Date -Format "yyyyMMdd"  
$logfilepath = "\\SourceServer\Script\FTPTest\"+$todaysdate+"Powershell.log"  
  
  
  
$getDate = Get-Date -Format "MMddyyyy"  
$FileName = "GreatwestMasterfile.txt"  
$Source1 = $SourceFilelocation+$FileName  
$BakupFileName = "GreatwestMasterfile_"+$getdate+".txt"  
$BakupFileLocation1 = $BakupFileLocation+$BakupFileName  
$RemoteLocation1 = "ftp://"+$SFTPServer+$RemoteLocation+"/"+ $FileName  
$EmailSubject = "FTP-greatwest -" + $datetime  
  
  
  
function WriteToLogFile ($message)  
{  
   #Add-content $logfilepath -value $message  
   (Get-Date).ToString() + "-" + $message >> $logfilepath  
}  
  
function Left   
{  
    param ($var)  
    #$var = "%yyahdakls"  
    if (($var -eq "") -or ($var -eq $null) -or ($var.Length -le 8))  
    {  
        $var = "99-99-99"  
        $result = $var.SubString(0,8)  
        $result  
    }  
    else  
    {  
        $result = $var.SubString(0,8)  
        $result  
    }  
}  
  
  
function Send-EmailToDBA  
{  
    param(  
        [Parameter(Mandatory = $true)][string]$emailBody,  
        [Parameter(Mandatory = $true)][string]$emailSubject  
    )  
  
    $EmailFrom = "NoReplyFromDBA@ada.org"   
    $EmailTo = "e-mail@test.com"   
  
    #Creating Subject for email  
    $datetime = Get-Date -Format "MM-dd-yyyy hh:mm:ss"   
  
    $SMTPServer = "smtp1.ada.org"   
    $mailer = new-object Net.Mail.SMTPclient($smtpserver)  
    $msg = new-object Net.Mail.MailMessage($EmailFrom, $EmailTo, $EmailSubject, $Emailbody)  
    $mailer.send($msg)  
     
  
} # end of function  
  
  
$LogMsg = "Validating Source File "+$Source  
    WriteToLogFile $LogMsg  
    Clear-Variable -Name LogMsg  
    $TestPath = Test-Path $Source1  
    If($TestPath -eq $true)  
    {  
        $LogMsg = "Validation success "+$Source1  
        WriteToLogFile $LogMsg  
        Clear-Variable -Name LogMsg  
         #Compress-Archive -Path $Source1 -Update -DestinationPath $DestinationBrokerCompressPath      
           
        ##Try  
       ## {  
  
              
  
            $LogMsg = "Estabilishing Connection with  "+$SFTPServer  
            WriteToLogFile $LogMsg  
            Clear-Variable -Name LogMsg  
            $ftp="ftp://"+$SFTPServer  
            $subfolder=$RemoteLocation  
            $ftpuri = $ftp + $subfolder  
            $uri=[system.URI] $ftpuri  
            $ftprequest=[system.net.ftpwebrequest]::Create($uri)  
            $ftprequest.Credentials=New-Object System.Net.NetworkCredential($SFTPUser,$pass)  
            $ftprequest.Method=[system.net.WebRequestMethods+ftp]::ListDirectoryDetails  
            $response=$ftprequest.GetResponse()  
            $strm=$response.GetResponseStream()  
            $reader=New-Object System.IO.StreamReader($strm,'UTF-8')  
            $list=$reader.ReadToEnd()  
            $lines=$list.Split("`n")  
            $count = $lines.Count  
            $LogMsg = "Estabilished Connection with  "+$SFTPServer  
            WriteToLogFile $LogMsg  
            Clear-Variable -Name LogMsg  
        
			$dateToMatch = Get-Date -Format "MM-dd-yy"  
		  
			$Found=0;  
			$LoopCount=0;  
	        $LogMsg = "Checking if File already exists on "+$SFTPServer  
            WriteToLogFile $LogMsg  
            Clear-Variable -Name LogMsg  
			while (($Found -eq 0) -and ($LoopCount -le $count))  
			{  
				$lines[$count]  
				$Element = $lines[$count]  
				$Element  
				  
				if ($Element -like "*GreatwestMasterfile.txt*")  
					{  
					$Found=1;  
					$ElementDate = left -var $Element   
					}  
				else  
					{  
					$count -= 1;  
					#$LoopCount  
					}  
				}  
			  
	  
			if (($Found -eq 0) -or (($Found -eq 1) -and ($ElementDate -ne $dateToMatch)))  
			{  
                $LogMsg = "Uploading File on "+$SFTPServer  
                WriteToLogFile $LogMsg  
                Clear-Variable -Name LogMsg  
				# FTP  
				# ** TODO Put all code to FTP here**  
                $ftprequest = [System.Net.FtpWebRequest]::Create("$RemoteLocation1")  
				$ftprequest = [System.Net.FtpWebRequest]$ftprequest  
				$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile  
				$ftprequest.Credentials = new-object System.Net.NetworkCredential($SFTPUser, $Pass)  
				$ftprequest.UseBinary = $true  
				$ftprequest.UsePassive = $true  
				$ftprequest.EnableSsl = $true  
				$filecontent = gc -en byte $Source1 -Raw  
				$ftprequest.ContentLength = $filecontent.Length  
                                $ftprequest.ContentLength  
				If(($filecontent.Length -eq 0) -or ($filecontent.Length -eq $null))  
				{  
                    $filecontent.Length  
                    Write-Host "Uploading EmptyFile"  
					$run = $ftprequest.GetRequestStream()  
                    Write-Host "GetRequestStream Test"  
					$run.Write('', 0, $filecontent.Length)  
                    Write-Host "Uploaded Not EmptyFile"  
	  
				}  
				Else   
				{  
                    Write-Host "Uploading Not EmptyFile"  
					$run = $ftprequest.GetRequestStream()  
                    $run  
					$run.Write($filecontent, 0, $filecontent.Length)  
                    Write-Host "Uploaded Not EmptyFile"  
				}  
					$run.Close()  
					$run.Dispose()  
					#$run = $ftprequest.GetRequestStream()  
					#$run.Write($filecontent, 0, $filecontent.Length)  
					#$FTPResponse = $FTPRequest.GetResponse()  
				  
	  
				Try  
				{   
                    $LogMsg = "Moving File from "+$Source1 +" To "+$BakupFileLocation1  
                    WriteToLogFile $LogMsg  
                    Clear-Variable -Name LogMsg  
					Move-Item -Path $Source1 -Destination $BakupFileLocation1 -Force  
                    $LogMsg = "File Moved to Backup folder "+$BakupFileLocation1  
                    WriteToLogFile $LogMsg  
                    Clear-Variable -Name LogMsg  
                         
				}  
				  
				catch [System.Management.Automation.ItemNotFoundException]  
				{  
					    $LogMsg = "File Does not exist to Move to Backup Folder - "+$Source1  
                        WriteToLogFile $LogMsg  
                        Clear-Variable -Name LogMsg  
				}  
				catch [System.IO.DirectoryNotFoundException]  
				{  
					    $LogMsg = "Backup Directory not found - "+$BakupFileLocation1  
                        WriteToLogFile $LogMsg  
                        Clear-Variable -Name LogMsg  
                      
				}  
					$CheckFile = "File : "+ $FileName +" - File has been uploaded on -"+$SFTPServer  
                    WriteToLogFile $CheckFile  
					Send-EmailToDBA -EmailBody $CheckFile -EmailSubject $EmailSubject  
					Clear-Variable -Name "CheckFile"   
				}               
			else  
			{  
				# Do not FTP  
				# ** TODO Put in error code here **  
				$CheckFile = "File :"+$FileName+" - is already exists on FTF Location - Not Uploaded."+$SFTPServer;   
                WriteToLogFile $CheckFile  
				Send-EmailToDBA -EmailBody $CheckFile -EmailSubject $EmailSubject  
				Clear-Variable -Name "CheckFile"  
		  
		    }  
       #}  
       #catch [System.Management.Automation.MethodInvocationException]  
       #  {  
       #     $LogMsg = "Unable to Estabilish connection from FTP Server- Make sure Password and remote Location is correct  - " +$SFTPServer  
       #     WriteToLogFile $LogMsg  
       #  }   
    }  
    else  
    {  
        $CheckFile = "File :"+$FileName+" - Does not exists on Local path - Not Uploaded."+$SFTPServer;   
        WriteToLogFile $CheckFile  
		Send-EmailToDBA -EmailBody $CheckFile -EmailSubject $EmailSubject  
        Clear-Variable -Name "CheckFile"  
    }  

Here is the error :
170359-powershellerror.jpg

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,407 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 45,111 Reputation points
    2022-02-03T20:07:17.363+00:00

    Shouldn't you be converting the $pass value into a secure string and using the secure string in the "New-Object System.Net.NetworkCredential($SFTPUser, $pass)"???

    0 comments No comments

  2. chetan Vishwakarma 146 Reputation points
    2022-02-04T11:53:10.177+00:00

    Fixed the isssue : here is the comment i have added for modified code : #Added this to fix

     $SFTPServer = "test.ftp.com"
     $SFTPUser = "user"
     $Pass = "password"
     $SourceFilelocation = "\\SourceServer\Script\FTPTest\Output_Files\"
     $BakupFileLocation = "\\SourceServer\Script\FTPTest\Backups\"
     $RemoteLocation = "//destinationDirectory/"
     $todaysdate=Get-Date -Format "yyyyMMdd"
     $logfilepath = "\\SourceServer\Script\FTPTest\"+$todaysdate+"Powershell.log"
    
    
    $getDate = Get-Date -Format "MMddyyyy"
    $FileName = "GreatwestMasterfile.txt"
    $Source1 = $SourceFilelocation+$FileName
    $BakupFileName = "GreatwestMasterfile_"+$getdate+".txt"
    $BakupFileLocation1 = $BakupFileLocation+$BakupFileName
    $RemoteLocation1 = "ftp://"+$SFTPServer+$RemoteLocation+"/"+ $FileName
    $EmailSubject = "FTP-greatwest -" + $datetime
    
    
    
    
    function WriteToLogFile ($message)
    {
       #Add-content $logfilepath -value $message
       (Get-Date).ToString() + "-" + $message >> $logfilepath
    }
    
    function Left 
    {
        param ($var)
        #$var = "%yyahdakls"
        if (($var -eq "") -or ($var -eq $null) -or ($var.Length -le 8))
        {
            $var = "99-99-99"
            $result = $var.SubString(0,8)
            $result
        }
        else
        {
            $result = $var.SubString(0,8)
            $result
        }
    }
    
    
     function Send-EmailToDBA
     {
         param(
             [Parameter(Mandatory = $true)][string]$emailBody,
             [Parameter(Mandatory = $true)][string]$emailSubject
         )
    
         $EmailFrom = "NoReplyFromDBA@ada.org" 
         $EmailTo = "e-mail@test.com" 
    
         #Creating Subject for email
         $datetime = Get-Date -Format "MM-dd-yyyy hh:mm:ss" 
    
         $SMTPServer = "smtp1.ada.org" 
         $mailer = new-object Net.Mail.SMTPclient($smtpserver)
         $msg = new-object Net.Mail.MailMessage($EmailFrom, $EmailTo, $EmailSubject, $Emailbody)
         $mailer.send($msg)
    
    
     } # end of function
    
    
    $LogMsg = "Validating Source File "+$Source
        WriteToLogFile $LogMsg
        Clear-Variable -Name LogMsg
        $TestPath = Test-Path $Source1
        If($TestPath -eq $true)
        {
            $LogMsg = "Validation success "+$Source1
            WriteToLogFile $LogMsg
            Clear-Variable -Name LogMsg
             #Compress-Archive -Path $Source1 -Update -DestinationPath $DestinationBrokerCompressPath    
    
            ##Try
           ## {
    
    
    
                $LogMsg = "Estabilishing Connection with  "+$SFTPServer
                WriteToLogFile $LogMsg
                Clear-Variable -Name LogMsg
                $ftp="ftp://"+$SFTPServer
                $subfolder=$RemoteLocation
                $ftpuri = $ftp + $subfolder
                $uri=[system.URI] $ftpuri
                $ftprequest=[system.net.ftpwebrequest]::Create($uri)
                $ftprequest.Credentials=New-Object System.Net.NetworkCredential($SFTPUser,$pass)
                $ftprequest.Method=[system.net.WebRequestMethods+ftp]::ListDirectoryDetails
                $response=$ftprequest.GetResponse()
                $strm=$response.GetResponseStream()
                $reader=New-Object System.IO.StreamReader($strm,'UTF-8')
                $list=$reader.ReadToEnd()
                $lines=$list.Split("`n")
                $count = $lines.Count
                $LogMsg = "Estabilished Connection with  "+$SFTPServer
                WriteToLogFile $LogMsg
                Clear-Variable -Name LogMsg
    
     $dateToMatch = Get-Date -Format "MM-dd-yy"
    
     $Found=0;
     $LoopCount=0;
             $LogMsg = "Checking if File already exists on "+$SFTPServer
                WriteToLogFile $LogMsg
                Clear-Variable -Name LogMsg
     while (($Found -eq 0) -and ($LoopCount -le $count))
     {
     $lines[$count]
     $Element = $lines[$count]
     $Element
    
     if ($Element -like "*GreatwestMasterfile.txt*")
     {
     $Found=1;
     $ElementDate = left -var $Element 
     }
     else
     {
     $count -= 1;
     #$LoopCount
     }
     }
    
    
     if (($Found -eq 0) -or (($Found -eq 1) -and ($ElementDate -ne $dateToMatch)))
     {
                    $LogMsg = "Uploading File on "+$SFTPServer
                    WriteToLogFile $LogMsg
                    Clear-Variable -Name LogMsg
    
    
                    $webclient = New-Object System.Net.WebClient  #Added this to fix
                    $webclient.Credentials = New-Object System.Net.NetworkCredential($SFTPUser,$pass) #Added this to fix
    
                    Try
                    {
    
                        $newUrl= $ftp+'/'+$FileName     #Added this to fix
                        $newUrl #Added this to fix
                        $uri = New-Object System.Uri($newUrl) #Added this to fix
                        $webclient.UploadFile($uri, $Source1)  #Added this to fix
    
                  } catch [Exception] {
    
                    $onNetwork = "0"
                    write-host $_.Exception.Message;
                }
     Try
     { 
                        $LogMsg = "Moving File from "+$Source1 +" To "+$BakupFileLocation1
                        WriteToLogFile $LogMsg
                        Clear-Variable -Name LogMsg
     Move-Item -Path $Source1 -Destination $BakupFileLocation1 -Force
                        $LogMsg = "File Moved to Backup folder "+$BakupFileLocation1
                        WriteToLogFile $LogMsg
                        Clear-Variable -Name LogMsg
    
     }
    
     catch [System.Management.Automation.ItemNotFoundException]
     {
         $LogMsg = "File Does not exist to Move to Backup Folder - "+$Source1
                            WriteToLogFile $LogMsg
                            Clear-Variable -Name LogMsg
     }
     catch [System.IO.DirectoryNotFoundException]
     {
         $LogMsg = "Backup Directory not found - "+$BakupFileLocation1
                            WriteToLogFile $LogMsg
                            Clear-Variable -Name LogMsg
    
     }
     $CheckFile = "File : "+ $FileName +" - File has been uploaded on -"+$SFTPServer
                        WriteToLogFile $CheckFile
     Send-EmailToDBA -EmailBody $CheckFile -EmailSubject $EmailSubject
     Clear-Variable -Name "CheckFile" 
     }             
     else
     {
     # Do not FTP
     # ** TODO Put in error code here **
     $CheckFile = "File :"+$FileName+" - is already exists on FTF Location - Not Uploaded."+$SFTPServer; 
                    WriteToLogFile $CheckFile
     Send-EmailToDBA -EmailBody $CheckFile -EmailSubject $EmailSubject
     Clear-Variable -Name "CheckFile"
    
         }
           #}
           #catch [System.Management.Automation.MethodInvocationException]
           #  {
           #     $LogMsg = "Unable to Estabilish connection from FTP Server- Make sure Password and remote Location is correct  - " +$SFTPServer
           #     WriteToLogFile $LogMsg
           #  } 
        }
        else
        {
            $CheckFile = "File :"+$FileName+" - Does not exists on Local path - Not Uploaded."+$SFTPServer; 
            WriteToLogFile $CheckFile
     Send-EmailToDBA -EmailBody $CheckFile -EmailSubject $EmailSubject
            Clear-Variable -Name "CheckFile"
        }
    
    0 comments No comments