user3191894
user3191894

Reputation:

Need to find most recent file from 1 of 2 sources then copy it

OK so back again with similar but different issue than yesterday, need to search directory and grab ONLY the most recent

$source =  "\\serverA\path\file*.txt"
$source2 =  "\\serverB\path\file*.txt"
$destination = "\\serverX\path\file.txt"
IF (Test-Path $source)
{
    Get-ChildItem $source | ForEach-Object
    {
        sort LastWriteTime -desc | select -first 1 |Copy-Item -Path $source -Destination $destination
    }
}
ELSE
{
    IF (Test-Path $source2)
    {
        Get-ChildItem $source2 | ForEach-Object
        {
            sort LastWriteTime -desc | select -first 1 |Copy-Item -Path $source2 -Destination $destination
        } 
    }
}

The above runs in a second, should copy a 500 MB file but it throws no errors

Upvotes: 0

Views: 56

Answers (3)

Esperento57
Esperento57

Reputation: 17472

try this

$sources =  "\\serverA\path\file*.txt", "\\serverB\path\file*.txt" 
$destination = "\\serverX\path\file.txt"

$sources | where { Test-Path $_ } | % {gci -Path $_ -File} | sort LastWriteTime -desc | select -First 1 | Copy-Item -Destination $destination 

Upvotes: 0

BenH
BenH

Reputation: 10044

In this section you are doing a foreach loop, passing in individual objects to sort.

Get-ChildItem $source | ForEach-Object {
    sort LastWriteTime -desc 

Instead you want to sort the whole collection:

Get-ChildItem $source | sort LastWriteTime -desc 

And here you are piping in an object but still declaring the Path:

|Copy-Item -Path $source

Clearing those two issues up, the first if block would look something like this:

IF (Test-Path $source) {
    Get-ChildItem $source | sort LastWriteTime -desc | select -first 1 | Copy-Item -Destination $destination
}

Upvotes: 2

Ashu
Ashu

Reputation: 1

Invoke-Command can be used. or, map a PSDrive to the server, and then run the command locally against that drive

Upvotes: -1

Related Questions