0

I have the latest Write-Log function from this module installed and wondered if it's possible to apply that function here rather than and or while using the verbose part of the transcript.

I want to now add in a try..catch where if it fails it using the Write-Log function to insert a record into the 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

For info this is the Write-Log function installed which still not sussed how it works given I've never used functions.

<# 
.Synopsis 
   Write-Log writes a message to a specified log file with the current time stamp. 
.DESCRIPTION 
   The Write-Log function is designed to add logging capability to other scripts. 
   In addition to writing output and/or verbose you can write to a log file for 
   later debugging. 
.NOTES 
   Created by: Jason Wasser @wasserja 
   Modified: 11/24/2015 09:30:19 AM   

   Changelog: 
    * Code simplification and clarification - thanks to @juneb_get_help 
    * Added documentation. 
    * Renamed LogPath parameter to Path to keep it standard - thanks to @JeffHicks 
    * Revised the Force switch to work as it should - thanks to @JeffHicks 

   To Do: 
    * Add error handling if trying to create a log file in a inaccessible location. 
    * Add ability to write $Message to $Verbose or $Error pipelines to eliminate 
      duplicates. 
.PARAMETER Message 
   Message is the content that you wish to add to the log file.  
.PARAMETER Path 
   The path to the log file to which you would like to write. By default the function will  
   create the path and file if it does not exist.  
.PARAMETER Level 
   Specify the criticality of the log information being written to the log (i.e. Error, Warning, Informational) 
.PARAMETER NoClobber 
   Use NoClobber if you do not wish to overwrite an existing file. 
.EXAMPLE 
   Write-Log -Message 'Log message'  
   Writes the message to c:\Logs\PowerShellLog.log. 
.EXAMPLE 
   Write-Log -Message 'Restarting Server.' -Path c:\Logs\Scriptoutput.log 
   Writes the content to the specified log file and creates the path and file specified.  
.EXAMPLE 
   Write-Log -Message 'Folder does not exist.' -Path c:\Logs\Script.log -Level Error 
   Writes the message to the specified log file as an error message, and writes the message to the error pipeline. 
.LINK 
   https://gallery.technet.microsoft.com/scriptcenter/Write-Log-PowerShell-999c32d0 
#> 
function Write-Log 
{ 
    [CmdletBinding()] 
    Param 
    ( 
        [Parameter(Mandatory=$true, 
                   ValueFromPipelineByPropertyName=$true)] 
        [ValidateNotNullOrEmpty()] 
        [Alias("LogContent")] 
        [string]$Message, 

        [Parameter(Mandatory=$false)] 
        [Alias('LogPath')] 
        [string]$Path='C:\Logs\PowerShellLog.log', 

        [Parameter(Mandatory=$false)] 
        [ValidateSet("Error","Warn","Info")] 
        [string]$Level="Info", 

        [Parameter(Mandatory=$false)] 
        [switch]$NoClobber 
    ) 

    Begin 
    { 
        # Set VerbosePreference to Continue so that verbose messages are displayed. 
        $VerbosePreference = 'Continue' 
    } 
    Process 
    { 

        # If the file already exists and NoClobber was specified, do not write to the log. 
        if ((Test-Path $Path) -AND $NoClobber) { 
            Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name." 
            Return 
            } 

        # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path. 
        elseif (!(Test-Path $Path)) { 
            Write-Verbose "Creating $Path." 
            $NewLogFile = New-Item $Path -Force -ItemType File 
            } 

        else { 
            # Nothing to see here yet. 
            } 

        # Format Date for our Log File 
        $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 

        # Write message to error, warning, or verbose pipeline and specify $LevelText 
        switch ($Level) { 
            'Error' { 
                Write-Error $Message 
                $LevelText = 'ERROR:' 
                } 
            'Warn' { 
                Write-Warning $Message 
                $LevelText = 'WARNING:' 
                } 
            'Info' { 
                Write-Verbose $Message 
                $LevelText = 'INFO:' 
                } 
            } 

        # Write log entry to $Path 
        "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append 
    } 
    End 
    { 
    } 
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Simon
  • 391
  • 4
  • 16
  • 2
    What is "the latest Write Log function"? – Mathias R. Jessen Jun 25 '19 at 09:22
  • whatever was installed - "To save time you can install it via PowerShell 5.0 using Install-Module MrAADAdministration. This will install write-log as well as other user functions to your system" – Simon Jun 25 '19 at 09:30
  • [here](https://stackoverflow.com/questions/53776641/how-do-i-create-log-file-time-user-who-run-the-script-and-what-happen-after-th/53776962#53776962) is how you write the output. Just put the `write-output` in the `catch{}`-block – T-Me Jun 25 '19 at 10:12
  • SO is not a place where other people write code for you. Please show the code where you attempt to use `Write-Log` and explain how the result was different from what you expected. – Ansgar Wiechers Jun 25 '19 at 11:19
  • Finally got there chaps – Simon Jun 25 '19 at 14:50

1 Answers1

0

Thanks for the input chaps finally got there in the end but made a few silly errors on the way.


$varfullpath = "C:\Users\Simon.Evans\Documents\ReferenceData__logfile.txt"
$sourceDirectory  = "C:\Users\Simon.Evans\Documents\Source Data\LNAT\Code_Maping.txt"
$destinationDirectory = "I:\Dev\BI\Projects\Powershell\Test Area\Source Data\LNAT\Code_Mapping.txt"

try{
    Copy-item -Force  -Verbose $sourceDirectory -Destination $destinationDirectory  -ErrorAction Stop 
    Write-log -Message "Copy from $sourceDirectory to $destinationDirectory suceeded" -path $varfullpath  
}
catch{
    $Error[0] | Write-Log -path $varfullpath                                                                            ##Example Error 1
    Write-log -Message "Copy from $sourceDirectory to $destinationDirectory Failed" -Level Error -path $varfullpath     ##Example Error 2
} 
Simon
  • 391
  • 4
  • 16