I am writing a script to copy all directories and items from one folder to another if they are more than seven days old.
I created a function for writing to a log. I call the function when I want to write something to the log. I am trying to list all items that I am copying. Normally when I do this I would call Out-File, but, again, this time I'm using a function. I've tried numerous iterations of getting the directory listing to log. It either doesn't log correctly (bad format), messes up the format of the rest of the log, or doesn't log at all for the directory listing. Can you please assist?
Basically, I want to write all directories or files greater than seven days old to my logfile. The lines that have an issue ends with Out-File $logfile -Append. I tried two different ways to get what I wanted.
$sourceDir = 'c:\temp\test\'
$targetDir = 'c:\temp\'
$date = (Get-Date).AddDays(-7)
$fileName = "TransfertoStream_"
$LogFile = "$($sourceDir)$($fileName)$(get-date -Format yyyyMMdd_HHmmss).log"
function LogWrite {
Param ([string]$logstring)
Add-Content $Logfile -Value $logstring
}
LogWrite "Created Log"
function Get-TimeStamp {
return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
}
LogWrite "$(Get-Timestamp) Created Timestamp "
LogWrite "$(Get-Timestamp) looking for all files with a date modified older than $($date)"
if (dir $source | %{ dir $_.FullName | ?{ $_.LastWriteTime -lt $date }}) {
LogWrite "$(Get-Timestamp) There are files to transfer"
LogWrite "$(Get-Timestamp) Here are the files and directories I am working on today"
Get-ChildItem -Path $sourceDir -Directory -Recurse -Force | % {
dir $_.FullName | ?{ $_.LastWriteTime -lt $date }
} | Out-File $LogFile -Append
Get-ChildItem $sourceDir -Recurse | % {
$dest = $targetDir + $_.FullName.SubString($sourceDir.Length)
if (!($dest.Contains('.')) -and !(Test-Path $dest)) {
mkdir $dest
}
Copy-Item $_.FullName -Destination $dest -Force | Out-File $logfile -Append
}
} else {
LogWrite "$(Get-TimeStamp) No files to transfer"
LogWrite "$(Get-TimeStamp) Ending"
}
The log looks like this, all the information at the end should be on no more than two lines...
Created Log
[07/03/18 17:23:34] Created Timestamp
[07/03/18 17:23:34] looking for all files with a date modified older than 06/26/2018 17:23:34
[07/03/18 17:23:34] There are files to transfer
[07/03/18 17:23:34] Here are the files and directories I am working on today
D i r e c t o r y : C : \ t e m p \ t e s t \ N e w f o l d e r
M o d e L a s t W r i t e T i m e L e n g t h N a m e
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- a - - - - 9 / 1 9 / 2 0 1 4 6 : 4 1 A M 8 8 4 7 9 8 2 0 6 S h a k e I t O f f - C o p y . m p 3
Can you think of a cleaner/simpler/more elegant way to get the file listing?
Add-Contentinstead ofOut-Filefor consistency.