gabe1975
gabe1975

Reputation: 11

Powershell test-path

Newbie help required here - I'm trying to search for the newest .csv file in F drive, then use Test-Path to check if that file is in the E drive. My script outputs the latest file name to screen which is correct - what I'm now trying to do is append $_latestFile.name to a Test-Path to see if this file is found in the folder in E drive.

Am I going about this the wrong way?

Thanks in advance.

$_sourcePath = "F:\"
$_destinationPath = "E:\"
$_FileType= @("*.*csv")
$_latestFile = Get-ChildItem -Recurse ($_sourcePath) -Include ($_FileType) | Sort-Object -Property $_.CreationTime | Select-Object -Last 1 
$_latestFile.name

Upvotes: 1

Views: 220

Answers (1)

Theo
Theo

Reputation: 61068

If your aim is to find a file in the $_destinationPath with the same name and modified date as the one you found on the $_sourcePath, you might do this:

$sourcePath ="F:\"
$destinationPath = "E:\"
$latestFile = Get-ChildItem -Path $sourcePath -Filter '*.csv' -File -Recurse | Sort-Object -Property $_.LastWriteTime | Select-Object -Last 1 
Write-Host "Latest CSV file in $sourcePath is '$($latestFile.Name)'"

$destFile = Get-ChildItem -Path $destinationPath -Filter "$($latestFile.Name)" -File -Recurse | Where-Object { $_.LastWriteTime -eq $latestFile.LastWriteTime }
if ($destFile) {
    Write-Host "Copy file found at '$($destFile.FullName)'" -ForegroundColor Green
}
else {
    Write-Host "Could not find a file '$($latestFile.Name)' with the same modified date in '$destinationPath'"-ForegroundColor Red
}

I have changed the property CreationTime to LastWriteTime in order to get the most recently updated file. CreationTime gets changed when a file is copied to another disk..

Also (thanks Steven) I changed the variable names from $_varname to $varname to avoid confusion with PowerShell's $_ Automatic Variable

Upvotes: 1

Related Questions