How do I create a log and erro log for a script?

Welcome Forums General PowerShell Q&A How do I create a log and erro log for a script?

This topic contains 9 replies, has 6 voices, and was last updated by

 
Participant
2 months, 1 week ago.

  • Author
    Posts
  • #161960

    Participant
    Topics: 3
    Replies: 5
    Points: 44
    Rank: Member

    Hi,

     

    Below is a simple script to move a file from one location to another, is there anyway this action when run can be inserted/appended into a log file if successful and an error file if unsuccessful and how would i go about approaching this please?

     

    ##########################################################################################################################################
    #Copies a single file from from one location to another location
    #Copy-item never delete extra files or folders in destination, but with -force it will overwrite if file already exists

    #Copies the contents of COde_mapping.txt in the LNAT folder in a local location onto a test location on the I drive

    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    Copy-item -Force -Recurse -Verbose $sourceDirectory -Destination $destinationDirectory

  • #161978

    Participant
    Topics: 9
    Replies: 423
    Points: 676
    Helping Hand
    Rank: Major Contributor
    Install-Module AZSBTools -Force -AllowClobber -Scope CurrentUser
    $LogFile   = ".\myLogFile-$(Get-Date -Format 'ddMMMMyyyy_hh-mm-ss_tt').txt"
    $ErrorFile = ".\myErrorFile-$(Get-Date -Format 'ddMMMMyyyy_hh-mm-ss_tt').txt"
    
    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    
    try {
        Copy-item -Force -Recurse -Verbose $sourceDirectory -Destination $destinationDirectory -ErrorAction Stop
        Write-Log 'Copying file',(Split-Path $sourceDirectory -Leaf),'from',(Split-Path $sourceDirectory),'to',(Split-Path $destinationDirectory),'complete' Green,Darkyellow,Green,Cyan,Green,Cyan,Green $LogFile 
    } catch {
        Write-Log 'Copying file',(Split-Path $sourceDirectory -Leaf),'from',(Split-Path $sourceDirectory),'to',(Split-Path $destinationDirectory),'failed' Magenta,Darkyellow,Yellow,Magenta,Yellow,Magenta,Yellow $ErrorFile
        Write-Log $_.Exception.Message Yellow $ErrorFile 
    }
    
  • #161979

    Participant
    Topics: 3
    Replies: 5
    Points: 44
    Rank: Member


    Install-Module : The 'Install-Module' command was found in the module 'PowerShellGet', but the module could not be loaded. For more information, run 'Import-Module PowerShellGet'.
    At line:1 char:1
    + Install-Module AZSBTools -Force -AllowClobber -Scope CurrentUser
    + ~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (Install-Module:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CouldNotAutoloadMatchingModule

     

    PS C:\> Import-Module PowerShellGet
    Import-Module : Errors occurred while loading the format data file:
    C:\Program Files\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\PackageManagement.format.ps1xml, , C:\Program
    Files\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\PackageManagement.format.ps1xml: The file was skipped because of the following validation exception: File C:\Program
    Files\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\PackageManagement.format.ps1xml cannot be loaded because running scripts is disabled on this system. For more information, see
    about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170..
    At line:1 char:1
    + Import-Module PowerShellGet
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [Import-Module], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

  • #162011

    Participant
    Topics: 3
    Replies: 5
    Points: 44
    Rank: Member

    Ok start again, is it possible to log the verbose part of this script into a CSV or TXT file? Is it also possible to include the runtime, machine and username

     

    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    Copy-item -Force -Verbose $sourceDirectory -Destination $destinationDirectory

     

    Expected outcome 4 columns of data get added to a file (TEST.csv), without overwriting the file, eg each time the script runs it inserts a new row???

    TIA

  • #162030

    Participant
    Topics: 0
    Replies: 15
    Points: 61
    Helping Hand
    Rank: Member

    A simple solution would be

    
    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    
    Try
    {
    Copy-item -Force -Recurse -Verbose $sourceDirectory -Destination $destinationDirectory -ErrorAction Stop
    "$(Get-Date)`tCopying files..." | Out-File -FilePath "C:\Scripts\ps.org\FileCopyLog.txt" -Append
    }
    Catch
    {
    "$(Get-Date)`tFailed to Copy files..." | Out-File -FilePath "C:\Scripts\ps.org\FileCopyLog.txt" -Append
    "$(Get-Date)`t$($Error[0].Exception.Message)" | Out-File -FilePath "C:\Scripts\ps.org\ErrorLog.txt" -Append
    }
    
    

     

    Also, it is possible to redirect this to the event log as well.

  • #162041
    js

    Participant
    Topics: 25
    Replies: 678
    Points: 1,629
    Helping Hand
    Rank: Community Hero
    script > output.txt 2> error.txt
    
  • #162173

    Participant
    Topics: 3
    Replies: 5
    Points: 44
    Rank: Member
    Okay so now I have the following which again works and Appends to a log file
    ####################################################################################################################################
    $varfullpath = "C:\Users\Simon.Evans\Documents\ReferenceData__logfile.txt"
    Start-Transcript -Path $varfullpath -Append
    write-output $varfullpath
    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    Copy-item -Force -Verbose $sourceDirectory -Destination $destinationDirectory
    Stop-Transcript
    ##########################################################################################################################################
    
    This is fine if it is successful by unsure how to add a try catch into this to catch the error exception and append this to the logfile also

    Any suggestions welcome

    TIA!

  • #162341

    Participant
    Topics: 3
    Replies: 5
    Points: 44
    Rank: Member
    PowerShell
    15 lines

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    Install-Module AZSBTools Force AllowClobber Scope CurrentUser
    $LogFile = ".\myLogFile-$(Get-Date -Format 'ddMMMMyyyy_hh-mm-ss_tt').txt"
    $ErrorFile = ".\myErrorFile-$(Get-Date -Format 'ddMMMMyyyy_hh-mm-ss_tt').txt"
    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    try {
    Copy-item Force Recurse Verbose $sourceDirectory Destination $destinationDirectory ErrorAction Stop
    Write-Log 'Copying file',(Split-Path $sourceDirectory Leaf),'from',(Split-Path $sourceDirectory),'to',(Split-Path $destinationDirectory),'complete' Green,Darkyellow,Green,Cyan,Green,Cyan,Green $LogFile
    } catch {
    Write-Log 'Copying file',(Split-Path $sourceDirectory Leaf),'from',(Split-Path $sourceDirectory),'to',(Split-Path $destinationDirectory),'failed' Magenta,Darkyellow,Yellow,Magenta,Yellow,Magenta,Yellow $ErrorFile
    Write-Log $_.Exception.Message Yellow $ErrorFile
    }
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Write-Log : Cannot process argument transformation on parameter 'Message'. Cannot convert value to type System.String.
    At line:12 char:15
    + ... Write-Log 'Copying file',(Split-Path $sourceDirectory -Leaf),'from' ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Write-Log], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Write-Log
  • #163737

    Participant
    Topics: 0
    Replies: 44
    Points: 235
    Helping Hand
    Rank: Participant

    @professorfudger

    You Can use below way as well to send the error message into log file.

    So Here, I have created simple Function called as "Write-log" which will handle the message in the log file & Make sure that you have to give correct log path here:

    Write-Log -Message "File is Copyied Successfully" -Path "D:\log.txt" -Level "Info"

    Function Write-Log($Message,$path,$Level)
    { 
    if (Test-Path $Path) { 
    Write-Verbose "Log file $Path already exists" 
    Return 
    } 
    
    elseif (!(Test-Path $Path)) { 
    Write-Verbose "Creating $Path." 
    $NewLogFile = New-Item $Path -Force -ItemType File 
    } 
    
    $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 
    switch ($Level) { 
    'Error' { 
    $LevelText = '[ERROR:]' 
    } 
    
    'Info' { 
    
    $LevelText = '[INFO:]' 
    } 
    } 
    
    "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append
    }
    
    [string]$sourceDirectory = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Mapping.txt"
    [string]$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"
    try{
    Copy-item -Force -Recurse -Verbose $sourceDirectory -Destination $destinationDirectory -ErrorAction stop
    Write-Log -Message "File is Copyied Successfully" -Path "D:\log.txt" -Level "Info" -verbose
    }
    catch{
    Write-Log -Message "$_" -Path "D:\log.txt" -Level "Error" -verbose
    }
  • #165373

    Participant
    Topics: 4
    Replies: 10
    Points: 75
    Rank: Member

    Have you investigated using the command Start-Transcript?

You must be logged in to reply to this topic.