Need assistance with generating log file

This topic contains 5 replies, has 2 voices, and was last updated by Profile photo of Kevyn Kevyn 2 weeks, 4 days ago.

  • Author
    Posts
  • #72049
    Profile photo of newbie
    newbie
    Participant

    Hello,

    I'm new to powershell and have a script that uploads a file. The log file generates, however it is blank. I am able to generate a valid log file when scheduling via task scheduler by adding ">C:\log.txt", but have not figured out how to append a date to the file. Plus I should be able to generate the valid log file via the script, not having to modify the task scheduler. Ideally, I would also like to have the log emailed to me with an appended date. Any assistance would be greatly appreciated.

    I suspect the problem lies somewhere here
    $session = New-Object WinSCP.Session
    $result | out-file "C:\log.txt"

    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
    
    # Set up session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "XXX.com"
        PortNumber = XXX
        UserName = "XXX"
        Password = "XXX"
        SshHostKeyFingerprint = "X"
    }
    
    $session = New-Object WinSCP.Session
    $result | out-file "C:\log.txt"
    
    try
    {
        # Connect
        $session.Open($sessionOptions)
    
        # Transfer files
        $session.PutFiles("\\server\share\*.csv", "/share/*").Check()
        $transferOptions.FilePermissions = $Null 
        $transferOptions.PreserveTimestamp = $False
    
    }
    finally
    {
        $session.Dispose()
    }
    
  • #72052
    Profile photo of Kevyn
    Kevyn
    Participant

    What results are you trying to output to the log file? I don't see in your code how you're defining/setting the value of your $result variable (Ex: $result = Get-Service). If the value is not defined, that would explain why the file is blank. You can always do a Write-Host in your code (Ex: Write-Host $result) to see if it has anything in it before you try to output it to the file. As for the other two pieces you mentioned.

    1. "...have not figured out how to append a date to the file"

    I assume you're talking about adding date/time text to the format of the file name so you know when it was written. You can use the Get-Date cmdlet to append a date (& time, if you want) to a file name. Looking at the help information (Ex: Get-Help Get-Date -full) will give you all the details you need, including examples on how to use the cmdlet. Below is an example where I append the current month(2 digits), the current date(2 digits), & the current year(2 digits) to the file name.

    $logFileName = 'log' + (Get-Date -Format MMddyy) + '.txt'
    

    You can then output your $result variable to it as follows:

    $result | Out-File C:\$logFileName
    

    2. "Ideally, I would also like to have the log emailed to me with an appended date."

    You can use the Send-MailMessage cmdlet to e-mail the log file to yourself and/or others. Again, the help information (Get-Help Send-MailMessage -full) will show you details on the cmdlet. Below is an example:

    Send-MailMessage -From yourself@domain.com -To yourself@domain.com -Subject "Today's log report" -Body "Here is today's log report" -SmtpServer smtp.domain.com -Port 587 -UseSSL -Credential (Get-Credential) -Attachments C:\$logFileName
    

    If you don't want to be prompted for credentials, you can specify the credentials in the file itself, though this is not secure.

    #Create user credentials
    $userID = "domain\username"
    $password = ConvertTo-SecureString 'YourPasswordHere' -AsPlainText -Force
    $creds = New-Object System.Management.Automation.PSCredential $userID, $password
    
    #Send e-mail message with log report attached
    Send-MailMessage -From yourself@domain.com -To yourself@domain.com -Subject "Today's log report" -Body "Here is today's log report" -SmtpServer smtp.domain.com -Port 587 -UseSSL -Credential $creds -Attachments C:\$logFileName
    

    I hope this helps.

  • #72070
    Profile photo of newbie
    newbie
    Participant

    Hi,

    The output I am trying to obtain is the text shown in the Console window after running the script manually (pressing green play button) using Powershell ISE. That output tells me if it was successful or not.

    If I schedule the task in task scheduler and add *>C:\log.txt, the log file does generate properly. However, the date and time does not append to the file name for obvious reasons. I feel like I'm so close.

    You have been of great help so far. Thank you.

  • #72079
    Profile photo of Kevyn
    Kevyn
    Participant

    Try the following:

    #Clear out the $error variable because this is where the error data will be stored if there is a failure when the script is run.
    $error.clear()
    
    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
    
    # Set up session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "XXX.com"
        PortNumber = XXX
        UserName = "XXX"
        Password = "XXX"
        SshHostKeyFingerprint = "X"
    }
    
    $session = New-Object WinSCP.Session
    $logFileName = 'log' + (Get-Date -Format ddMMyy_HHmm) + '.txt'
    
    try
    {
        # Connect
        $session.Open($sessionOptions)
    
        # Transfer files
        $session.PutFiles("\\server\share\*.csv", "/share/*").Check()
        $transferOptions.FilePermissions = $Null 
        $transferOptions.PreserveTimestamp = $False
    
    }
    finally
    {
        If($error.count -gt 0)
        {
            #Write error to the log file
            $error | Out-File C:\$logFileName
        }
        Else
        {
            #If there are no failures in the "Try" script block, then write a success status to the log file.
            "No errors occurred." | Out-File C:\$logFileName
        }
        $session.Dispose()
    }
    

    If you don't want a log file to be generated when there is no failure/error, then you can change your Finally{} script block to the following:

    finally
    {
        If($error.count -gt 0)
        {
            #Write error to the log file
            $error | Out-File C:\$logFileName
        }
        $session.Dispose()
    }
    

    You can find out more about the Try/Catch/Finally script block in the Powershell help file (i.e. Get-Help about_Try_Catch_Finally -full). Hope this helps.

  • #72082
    Profile photo of newbie
    newbie
    Participant

    So the only thing I was missing was $error? (smacks forehead)
    $error | Out-File C:\$logFileName

    I was able to get the e-mail log file to work, though did it a bit differently. Thank you very much for all your help.

    #SMTP server name
         $smtpServer = "XXX.com"
    
         #Creating a Mail object
         $msg = new-object Net.Mail.MailMessage
    
         #Creating SMTP server object
         $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    
    $EmailText = ""
    
    $Text = get-content "C:\filelocation\$logfilename"
    
    foreach($line in $Text){
    $EmailText+=$line
    $EmailText+="`r`n"}
    
    $msg.To.Add("person@XXXX.com")
    
         #Email structure
         $msg.From = "test@test.com"
         #$msg.ReplyTo = "replyto@xxxx.com"
         $msg.subject = "Subject Message"
         $msg.body = $EmailText
         # attachments = "C:\filelocation\$logfilename"
    
         #Sending email
         $smtp.Send($msg)
  • #72155
    Profile photo of Kevyn
    Kevyn
    Participant

    Very nice....Not a problem. Glad I could help.

You must be logged in to reply to this topic.