需要从2个来源中的1个中找到最新文件然后复制它

时间:2016-10-21 17:02:04

标签: powershell

好的,所以再次回到类似但不同于昨天的问题,需要搜索目录并抓住最近的

$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
        } 
    }
}

以上运行一秒钟,应该复制一个500 MB的文件,但它不会抛出错误

3 个答案:

答案 0 :(得分:2)

在本节中,您正在进行foreach循环,将单个对象传递给sort

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

相反,您想要对整个集合进行排序:

Get-ChildItem $source | sort LastWriteTime -desc 

在这里,你在一个对象中管道但仍然声明路径:

|Copy-Item -Path $source

清除这两个问题,第一个if块看起来像这样:

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

答案 1 :(得分:0)

试试这个

$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 

答案 2 :(得分:-1)

可以使用Invoke-Command。 或者,将PSDrive映射到服务器,然后针对该驱动器在本地运行该命令