Skip to content

Instantly share code, notes, and snippets.

@kspeeckaert
Created April 14, 2022 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kspeeckaert/0e662152737527460763b0b96f9b5785 to your computer and use it in GitHub Desktop.
Save kspeeckaert/0e662152737527460763b0b96f9b5785 to your computer and use it in GitHub Desktop.
Remote Copy
[cmdletbinding()]
param (
[Parameter(Mandatory)][System.IO.DirectoryInfo]$SourceFolder,
[Parameter(Mandatory)][string]$RemoteFolder,
[Parameter(Mandatory)][string]$Server,
[Parameter(Mandatory)][pscredential]$Credential
)
function New-TemporaryDirectory {
[OutputType([System.IO.DirectoryInfo])]
param (
[String]$Parent = [System.IO.Path]::GetTempPath()
)
[string]$Name = [System.Guid]::NewGuid()
New-Item -ItemType Directory -Path (Join-Path $Parent $Name) -ErrorAction Stop
}
function New-TemporaryFileExt {
[OutputType([System.IO.FileInfo])]
param (
[String]$Parent = [System.IO.Path]::GetTempPath(),
[String]$Extension = '.tmp'
)
[string]$Name = [System.Guid]::NewGuid()
New-Item -ItemType File -Path ((Join-Path $Parent $Name) + $Extension) -ErrorAction Stop
}
$Files = @(Get-ChildItem -Path $SourceFolder -File)
if ($Files.Count -eq 0) {
Write-Warning "No files found, aborting..."
Exit
} else {
Write-Verbose "$($Files.Count) file(s) to copy"
}
Write-Host "Connecting to $Server with user $($Credential.UserName)..."
$Session = New-PSSession -ComputerName $Server -Credential $Credential
try {
Write-Verbose "Creating archive..."
$Archive = New-TemporaryFileExt -Extension '.zip'
Compress-Archive -Path "$($SourceFolder.FullName)\*" -DestinationPath $Archive -Force
Write-Verbose "Files archived to $($Archive.FullName)"
try {
Write-Verbose "Creating temporary folder on $Server..."
$TempFolder = Invoke-Command `
-Session $Session `
-ScriptBlock ${Function:New-TemporaryDirectory} `
-ArgumentList $RemoteFolder
# Copy zip file to remote folder
Write-Verbose "Folder name: $($TempFolder.FullName)"
Copy-Item $Archive -ToSession $Session -Destination $TempFolder -ErrorAction Stop
# Generate remote archive name
$DestArchive = [IO.Path]::Combine($TempFolder.FullName, $Archive.Name)
}
finally {
# Remove the local copy of the archive
Remove-Item $Archive -Force -ErrorAction SilentlyContinue
}
# Extract the archive on the remote server
Invoke-Command `
-Session $Session `
-ScriptBlock {
try {
Expand-Archive -Path $Using:DestArchive -DestinationPath $Using:TempFolder
} finally {
Remove-item $Using:DestArchive -Force
}
}
Write-Host "Files copied to $($TempFolder.FullName) on $Server" -ForegroundColor Green
$TempFolder.FullName | Set-Clipboard
}
catch {
Write-Host "Failed to copy files to $($TempFolder.FullName) on ${Server}: $($_.Exception.Message)" -ForegroundColor Red
}
finally {
Remove-PSSession -Session $Session
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment