繁体   English   中英

PowerShell 复制文件夹和子文件夹中的所有文件不早于 300 分钟

[英]PowerShell Copy All Files in Folders and Sub=Folders Not older than 300 minutes

我试图复制不超过 300 分钟的文件夹和子文件夹中的所有文件,但我得到的代码只复制主文件夹中的文件,它不会复制子文件夹中的文件。 在目的地我不想维护原始文件的文件夹结构,我只想将所有原始文件放入一个特定的目标文件夹中。 这是我的代码:

Powershell -NoL -NoP -C "&{$ts=New-TimeSpan -M 300;"^
 "Get-ChildItem "C:\Origin" -Filter '*.dat'|?{"^
 "$_.LastWriteTime -gt ((Get-Date)-$ts)}|"^
 %%{Copy-Item $_.FullName 'C:\Destination'}}"

有人可以帮我吗? 提前致谢。

这是为您修改的脚本,您可以另存为“Copy-Unique.ps1”,您可以从批处理文件运行。

function Copy-Unique {
    # Copies files to a destination. If a file with the same name already exists in the destination,
    # the function will create a unique filename by appending '(x)' after the name, but before the extension. 
    # The 'x' is a numeric sequence value.
    [CmdletBinding(SupportsShouldProcess)]  # add support for -WhatIf switch
    Param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [Alias("Path")]
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$SourceFolder,

        [Parameter(Mandatory = $true, Position = 1)]
        [string]$DestinationFolder,

        [Parameter(Mandatory = $false)]
        [int]$NewerThanMinutes = -1,

        [Parameter(Mandatory = $false)]
        [string]$Filter = '*',

        [switch]$Recurse
    )

    # create the destination path if it does not exist
    if (!(Test-Path -Path $DestinationFolder -PathType Container)) {
        Write-Verbose "Creating folder '$DestinationFolder'"
        $null = New-Item -Path $DestinationFolder -ItemType 'Directory' -Force
    }
    # get a list of file FullNames in this source folder
    $sourceFiles = @(Get-ChildItem -Path $SourceFolder -Filter $Filter -File -Recurse:$Recurse)
    # if you want only files not older than x minutes, apply an extra filter
    if ($NewerThanMinutes -gt 0) {
        $sourceFiles = @($sourceFiles | Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-$NewerThanMinutes) })
    }
    foreach ($file in $sourceFiles) {
        # get an array of all filenames (names only) of the files with a similar name already present in the destination folder
        $destFiles = @((Get-ChildItem $DestinationFolder -File -Filter "$($file.BaseName)*$($file.Extension)").Name)
        # for PowerShell version < 3.0 use this
        # $destFiles = @(Get-ChildItem $DestinationFolder -Filter "$baseName*$extension" | Where-Object { !($_.PSIsContainer) } | Select-Object -ExpandProperty Name)

        # construct the new filename
        $newName = $file.Name
        $count = 1
        while ($destFiles -contains $newName) {
            $newName = "{0}({1}){2}" -f $file.BaseName, $count++, $file.Extension
        }
        # use Join-Path to create a FullName for the file
        $newFile = Join-Path -Path $DestinationFolder -ChildPath $newName
        Write-Verbose "Copying '$($file.FullName)' as '$newFile'"

        $file | Copy-Item -Destination $newFile -Force
    }
}

# you can change the folder paths, file pattern to filter etc. here
$destFolder = Join-Path -Path 'C:\Destination' -ChildPath ('{0:yyyy-MM-dd_HH-mm}' -f (Get-Date))
Copy-Unique -SourceFolder "C:\Origin" -DestinationFolder $destFolder -Filter '*.dat' -Recurse -NewerThanMinutes 300

将代码更改为现在采用datetime时间 object 进行比较而不是分钟数。 这可能使代码更容易理解,但肯定更灵活。

function Copy-Unique {
    # Copies files to a destination. If a file with the same name already exists in the destination,
    # the function will create a unique filename by appending '(x)' after the name, but before the extension. 
    # The 'x' is a numeric sequence value.
    [CmdletBinding(SupportsShouldProcess)]  # add support for -WhatIf switch
    Param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [Alias("Path")]
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$SourceFolder,

        [Parameter(Mandatory = $true, Position = 1)]
        [string]$DestinationFolder,

        [string]$Filter = '*',

        [datetime]$NewerThan = [datetime]::MinValue,

        [switch]$Recurse
    )

    # create the destination path if it does not exist
    if (!(Test-Path -Path $DestinationFolder -PathType Container)) {
        Write-Verbose "Creating folder '$DestinationFolder'"
        $null = New-Item -Path $DestinationFolder -ItemType 'Directory' -Force
    }
    # get a list of file FullNames in this source folder
    $sourceFiles = @(Get-ChildItem -Path $SourceFolder -Filter $Filter -File -Recurse:$Recurse)
    # if you want only files newer than a certain date, apply an extra filter
    if ($NewerThan -gt [datetime]::MinValue) {
        $sourceFiles = @($sourceFiles | Where-Object { $_.LastWriteTime -gt $NewerThan })
    }
    foreach ($file in $sourceFiles) {
        # get an array of all filenames (names only) of the files with a similar name already present in the destination folder
        $destFiles = @((Get-ChildItem $DestinationFolder -File -Filter "$($file.BaseName)*$($file.Extension)").Name)
        # for PowerShell version < 3.0 use this
        # $destFiles = @(Get-ChildItem $DestinationFolder -Filter "$baseName*$extension" | Where-Object { !($_.PSIsContainer) } | Select-Object -ExpandProperty Name)

        # construct the new filename
        $newName = $file.Name
        $count = 1
        while ($destFiles -contains $newName) {
            $newName = "{0}({1}){2}" -f $file.BaseName, $count++, $file.Extension
        }
        # use Join-Path to create a FullName for the file
        $newFile = Join-Path -Path $DestinationFolder -ChildPath $newName
        Write-Verbose "Copying '$($file.FullName)' as '$newFile'"

        $file | Copy-Item -Destination $newFile -Force
    }
}

# you can change the folder paths, file pattern to filter etc. here
$destFolder = Join-Path -Path 'D:\Destination' -ChildPath ('{0:yyyy-MM-dd_HH-mm}' -f (Get-Date))
Copy-Unique -SourceFolder "C:\Origin" -DestinationFolder $destFolder -Filter '*.dat' -Recurse -NewerThan (Get-Date).AddMinutes(-300)

当您将上述代码保存为“C:\Scripts\Copy-Unique.ps1”时,您可以从批处理文件中调用它,例如:

Powershell.exe -NoLogo -NoProfile -File "C:\Scripts\Copy-Unique.ps1"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM