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

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

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 
}

[quote quote=161978][/quote]
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: (:slight_smile: [Import-Module], RuntimeException
+ FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

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

A simple solution would be

[pre]

[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
}

[/pre]

 

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

script > output.txt 2> error.txt
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!

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

@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
}

Have you investigated using the command Start-Transcript?