functions/common/Copy-NewestItem.ps1

<#
.SYNOPSIS
Copies the most recently modified item from a source path to a destination.
 
.DESCRIPTION
The Copy-NewestItem function identifies the most recently modified file or folder in the given source path and copies it to the specified destination. Optionally, the copy can overwrite existing files using the -Force switch.
 
.PARAMETER FromPath
The path from which to find the newest item.
 
.PARAMETER Destination
The destination path where the newest item will be copied.
 
.PARAMETER Force
If specified, allows overwriting existing items at the destination.
 
.EXAMPLE
Copy-NewestItem -FromPath "C:\Logs" -Destination "C:\Backup"
 
Copies the most recently modified file or folder from C:\Logs to C:\Backup.
 
.EXAMPLE
Copy-NewestItem -FromPath "C:\Logs" -Destination "C:\Backup" -Force
 
Same as above, but will overwrite the file if it already exists in the destination.
 
.NOTES
Alias: Copy-Newest
Renamed on 2025-06-08 for verb compliance.
#>

function Copy-NewestItem {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$FromPath,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Destination,

        [switch]$Force
    )

    if (-not (Test-Path -Path $FromPath)) {
        throw "The path '$FromPath' does not exist."
    }

    $newestItem = Get-ChildItem -Path $FromPath | Sort-Object LastWriteTime -Descending | Select-Object -First 1

    if (-not $newestItem) {
        throw "No items found in '$FromPath'."
    }
    
    Copy-Item -Path $newestItem.FullName -Destination $Destination -Force:$Force
}

Set-Alias -Name Copy-Newest -Value Copy-NewestItem -Description 'Prevent breaking scripts using Copy-Newest after function has been renamed (2025-06-08).'