Search code examples
powershellpowershell-4.0

Linking two array variables in one line


Right now, I have an array called $vlog that shows the most recent instance of each log file in a certain folder $logpathfor each version of a particular version of a service $verno running on a machine. It displays the filename and the last write time.

$VLog = foreach ($log in $verno) {
    Get-ChildItem $LogPath | 
        Where-Object {$_.Name -like "*$log-*"} | 
        Select-Object -last 1 | Select-Object Name, LastWriteTime
}

Furthermore, I'm using a mix of Trim() and -replace to cut most of the name down to ONLY show the corresponding version number contained within the log file name.

$vname = $vlog.name.Trim('service.logfile.prefix-') -replace ".{9}$"

Basically, it's cutting the end of the file (containing a date and the extension .log), as well as a specific preceding bit of text that's a constant at the beginning of each file. This all works great.

Now here's the trouble.

I need to get two items from this logfile data ($vname, which is the version number), and the corresponding LastWriteTime for the logfile for THAT specific version. I need that as an array, which will be further put into a variable for an email

What I need it to say is Service instance version #VERSION# was last logged at #VERSION'S LAST WRITE TIME#.

This is what I have right now:

$mailvar = foreach ($version in $vname) {
    "Service instance version $version was last logged at $PLEASEHELP."
}

I can get it to display the correct number of instances of that sentence, with the correct version number per sentence, but I can't get the time to display the last write time corresponding to that version number.


Solution

  • I believe what you're looking for is the FileInfo property LastWriteTime. Here's your example simplified:

    foreach ($log in $verno) {
        $file = (Get-ChildItem -Path $LogPath -Filter "*$log-*")[-1]
        $version = $file.Name.Trim('service.logfile.prefix-') -replace '.{9}$'
        $stamp = $file.LastWriteTime | Get-Date -UFormat '%Y-%m-%d %H:%M:%S'
    
        'Service instance version {0} was last logged at {1}' -f $version, $stamp
    }