Generic/CopySelf.ps1
<#
.SYNOPSIS Copies the currently running script to a specified destination. #> function Copy-Self { [CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory = $false)] [string]$TargetPath = $null, [Parameter( Mandatory = $true, HelpMessage = "Specify the destination file or folder path" )] [string]$DestinationPath ) if ($TargetPath -eq $null) { $TargetPath = $PSCommandPath if (-not $TargetPath) { $TargetPath = $MyInvocation.MyCommand.Path } if (-not $TargetPath) { Throw "Unable to determine script path. This function must be called from a script file." } } if (Test-Path -Path $DestinationPath -PathType Container) { $fileName = [IO.Path]::GetFileName($TargetPath) $DestinationPath = Join-Path -Path $DestinationPath -ChildPath $fileName } else { $destDir = Split-Path -Path $DestinationPath -Parent if ($destDir -and -not (Test-Path $destDir)) { if ($PSCmdlet.ShouldProcess($destDir, "Create directory")) { New-Item -Path $destDir -ItemType Directory -Force | Out-Null } } } if ($PSCmdlet.ShouldProcess($TargetPath, "Force copy to $DestinationPath")) { Copy-Item -Path $TargetPath ` -Destination $DestinationPath ` -Force ` -ErrorAction Stop Write-Verbose "Copied: '$TargetPath' -> '$DestinationPath'" } } |