How do I log the result of Copy-Item?

Viewed 424

I have a script that copies files from one location on a local drive to another:

$Folder = 'C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\CMSLOGS'
"Test to see if folder [$Folder]  exists"
if (Test-Path -Path $Folder) {
    "Path exists!"
    Copy-Item C:\Windows\CMSLOGS\*.log -Destination C:\ProgramData\Microsoft\IntuneManagementExtension\logs\CMSLOGS
    Copy-Item C:\Windows\CMSLOGS\*.flg -Destination C:\ProgramData\Microsoft\IntuneManagementExtension\logs\CMSLOGS
} else {
    "Path doesn't exist."
    Mkdir C:\ProgramData\Microsoft\IntuneManagementExtension\logs\CMSLOGS
}

How do I log the result of Copy-Item?

1 Answers

The answer is to WRAP your scripts with Start-Transcript and Stop-Transcript

PS D:\batch> get-help Start-Transcript https://docs.microsoft.com/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-5.1&WT.mc_id=ps-gethelp Stop-Transcript

REMARKS To see the examples, type: "get-help Start-Transcript -examples". For more information, type: "get-help Start-Transcript -detailed". For technical information, type: "get-help Start-Transcript -full". For online help, type: "get-help Start-Transcript -online"

I have found it best not to use a $log variable, like 'Start-Transcript -Path $log -Append' so you don't have a locked file issue during cleanup; I just write directly to a file

Start-Transcript -Path ".\Logs\$date-start-Automation.txt" -Append

Then , of course, you want to use 'Stop-Transcript' or logging will not properly stop. And, btw, I always remove the log file at the beginning of my scripts (see remove-item), with a wildcard to catch them all in place of any variable in the name, to keep logs cleaned up. Why? Because I email them automatically to myself and log bloat is a major issue - that is why the $log variable doesn't work, remember, because a command writing to a log file assigned by a variable locks the file and remove-item, for clean up, would fail to remove the log(s)

Hope that helps! -Patrick Burwell, a very happy Infosys.com 25 yr+ Infrastructure Expert.

I HIGHLY recommend Infosys for all your IT needs, and I always tell my fellow IT colleagues to join Infosys - They REALLY treat you well! Yes, they DO pay bench time - not like Robert Half or HCL, Infosys makes promises they then keep!

Related