Copy files from workstation to server specifying credentials

Building on top of my previous post on securing a password here and using it to join to a domain here, we can use this to define a user account to copy files from a workstation to a server.

Lines 1 through 5 should look familiar since we’ve already used them before previously.

On line 7 we are creating a new Powershell mapped drive using the credentials we defined in lines 1 through 5 labeled “B” to a DFS share in this case but can be mapped to any UNC path.

Lines 9 and 10 is actually copying the particular files we want to copy, this will also rename them to the following format “DESKTOP-JEDI-2021-11-10.ext”
Note: You will have to define the file extension for each file copied or it will not have one.

Lastly on line 12 we’re removing the “B” drive so that it can be re-used again and it’s just cleaner to close the connection when not needed.

$File = "C:\Scripts\Password.txt"
$Key = (1..32)
$username = "contoso.com\srvc_copy_files"
$Password = Get-Content $File | ConvertTo-SecureString -Key $Key
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName,$Password

New-PSDrive -Name B -PSProvider FileSystem -Root \\contoso.com\path\to\directory -Credential $cred

Copy-Item -Path "c:\path\to\file.bak.gz" -Destination B:\"$($env:COMPUTERNAME + "-" + $(Get-Date -UFormat "%Y-%m-%d")).bak.gz"
Copy-Item -Path "c:\path\to\file.bak.gz.SHA-1" -Destination B:\"$($env:COMPUTERNAME + "-" + $(Get-Date -UFormat "%Y-%m-%d")).gz.SHA-1"

Remove-PSDrive -Name B

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.