I have a PowerShell script which copies some file from one folder to another folder and I also have code to create a log file and add the steps that are performed by the script to the log file.
Below is the code -
[CmdletBinding()]
Param (
[string]$destRoot = "C:\Program Files\Demo",
[string]$BackUpFolder = "C:\Program Files\Backup"
)
$scriptPath = $PSScriptRoot
$logFilePath = Join-path $scriptPath "FileDeployment.log"
# If log file exists, then clear its contents
if (Test-Path $logFilePath) { clear-content -Path $logFilePath }
# It displays the date and time of execution of powershell script in log file.
$log = "Date Of Testing: {0} " -f (Get-Date)
$logString = "Process Started."
add-content -Path $logFilePath -Value $log -Force
add-content -Path $logFilePath -Value $logString -Force
add-content -Path $logFilePath -Value "`n" -Force
# Code to take back of programs folder
$ProgramFilesBackUp = "$BackUpFolder\BackupPrograms"
$ProgramsFiles = "$destRoot\Programs\*"
Copy-Item $ProgramsFiles $ProgramFilesBackUp -Recurse -Force -Verbose
The -Verbose
displays all the files names along with its path getting copied from Programs folder to BackupPrograms folder but it fails to add that output to my log files which is shown on command shell. I tried something like this but it overwrites the previous output present in the log file.
Copy-Item $ProgramsFiles $ProgramFilesBackUp -Recurse -Force -Verbose *> $logFilePath
I also tried the below code as well by copying the output generated by verbose to a new file and then try to append the content of the file to my log file, here it copied the content but not in the proper format.
$NewText= "$PSScriptRoot\s.txt"
Copy-Item $ProgramsFiles $ProgramFilesBackUp -Recurse -Force -Verbose *> $NewText
Get-Content $NewText | Out-File $logFilePath -Verbose -Append
Below is the format the way in which it copied the content.