Copying a file from a remote session using Powershell

One of the challenges of using powershell remoting between domains is that while you can certainly set up remoting, there is no Powershell way of getting files from this remote session. In order to tackle this problem, mostly because sometimes I just want to work with things locally, or even back them up locally, I wrote a fairly short and simple script to copy a file back to my local workstation.

I should probably use this opportunity to point out that if you’re using the ISE environment to open sessions to your remote computers, you can, as of WMF5, simply punch “Psedit yourfile.txt” into the scripting pane and it will open the remote file in your ISE environment. You can get the latest WMF preview here.

Anyway, sometimes the goal isn’t just to edit a remote file, but for some reason to bring it from the remote machine to your local machine. And for that I created the get-sessionfile.ps1 script.

param
(
    [Parameter(Mandatory = $true)][string]$computer,
    [Parameter(Mandatory = $true)][string]$remotepath,  
    [Parameter(Mandatory = $true)][string]$localpath,
    [Parameter(Mandatory = $true)][pscredential]$creds
)

$session = New-PSSession $computer -UseSSL -Credential $creds
$remotecontent = Invoke-Command -Session $session {Get-Content $args[0]} -args $remotepath
set-content $localpath $remotecontent -Force
Remove-PSSession $session

The script itself is very little magic. You provide the require parameters. The script assumes you’re doing this from one domain to another with no trust between them, because if you’re working inside a domain, you could usually just use UNC paths to copy things. If you want to use this without SSL and alternative credentials, just delete the mandatory Parameter pscredential, and remove the two flags from the New-PSSession cmdlet.

What this does is essentially read the contents of whatever file you want to copy, and write those exact contents to a file created locally, essentially “copying” the file, although this will not of course maintain meta-data about the file, such as the last write time.

There are a ton of ways of improving the script, the most glaringly obvious one is there is currently no way to send the file back, but this should at least help you get going, and solve exactly one problem.

Advertisements
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: