Creating LastWriteTime as a Variable

Hello All,

I am pretty new so please excuse the rather rudimentary question.

I am trying to write a script that will check my backups and report the time and status to me. I am currently hung up on trying to get the LastWriteTime into the output by assigning the date it pulls to a variable. Here is what I have in my mind so far that currently does not work:

$LogFile=C:\Users\john\iDrive\logs\account\IDL-01\*.xml | Sort-Object | Select-Object -Last 1
$BackupLogDate=$LogFile | select LastWriteTime.ToString(“yyyy-MM-dd HH:mm”)
Write-Host “The backup on $BackupLogDate was $BackupStatus”

The error I keep getting is “Cannot run a document in the middle of a pipeline”, which I am now realizing I do not understand pipelines well enough to diagnose the issue.

Any help would be greatly appreciated!

Hi Jason

Use Get-ChildItem to enumerate the files in the path you specified

$LogFile = Get-ChildItem -Path 'C:\Users\john\iDrive\logs\account\IDL-01\*.xml' | Sort-Object -Property LastWriteTime | Select-Object -Last 1

Then use Select-Object with the ExpandProperty parameter to grab the value of the LastWriteTime property

$BackupLogDate = $LogFile | Select-Object -ExpandProperty LastWriteTime

You could also do it all in one line

$BackupLogDate = Get-ChildItem -Path 'C:\Users\john\iDrive\logs\account\IDL-01\*.xml'| Sort-Object -Property LastWriteTime | Select-Object -Last 1 -ExpandProperty LastWriteTime

Hey Christian,

Thanks so much for your help! That was exactly what I was looking for. I really appreciate the explanation as well as I am trying to teach myself powershell by making this script and its a bit trial by fire!

Again, I truly appreciate your effort and assistance!

All best…


My pleasure :slight_smile: