QiitaDrive.psm1

function Copy-QiitaItem {
    # .EXTERNALHELP QiitaDrive-help.xml
    [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Path')]
    param(
        [Parameter(Mandatory, Position = 0, ParameterSetName = 'Path')]
        [string[]]$Path,

        [Parameter(Mandatory, ParameterSetName = 'LiteralPath', ValueFromPipelineByPropertyName)]
        [Alias('PSPath')]
        [string[]]$LiteralPath,

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

    begin {
        # Resolve destination to full path (e.g. "c:" → "c:\tmp\qiita", "c:hoge.md" → "c:\tmp\qiita\hoge.md")
        $resolvedDest = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination)
        $destIsDir = Test-Path -LiteralPath $resolvedDest -PathType Container
    }

    process {
        if ($PSCmdlet.ParameterSetName -eq 'LiteralPath') {
            # Convert provider-qualified PSPath to drive-qualified path for resolution
            # (provider-qualified paths fail because PSDriveInfo is null in that context)
            $drivePaths = @($LiteralPath | ForEach-Object {
                if ($_ -match '::') { $_.Substring($_.IndexOf('::') + 2) } else { $_ }
            })
            $sources = @(Resolve-Path -LiteralPath $drivePaths)
        } else {
            $sources = @(Resolve-Path -Path $Path)
        }
        if (-not $sources) { return }

        if ($sources.Count -gt 1 -and -not $destIsDir) {
            throw 'Destination must be an existing directory when copying multiple items.'
        }

        foreach ($src in $sources) {
            $name = Split-Path $src.ProviderPath -Leaf
            $destFile = if ($destIsDir) { Join-Path $resolvedDest $name } else { $resolvedDest }
            if ($PSCmdlet.ShouldProcess("$name → $destFile", 'Copy')) {
                Get-Content -LiteralPath $src -ErrorAction Stop | Set-Content -LiteralPath $destFile -Encoding utf8
            }
        }
    }
}