How can I copy from local to a remote location with credentials in PowerShell?

10,534

Solution 1

Copy-Item doesn't support the -credential parameter, This does parameter appear but it is not supported in any Windows PowerShell core cmdlets or providers"

You can try the below function to map a network drive and invoke copy

Function Copy-FooItem {

param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$True)]
        [string]$username,
        [Parameter(Mandatory=$true,ValueFromPipeline=$True)]
        [string]$password
        )

$net = New-Object -com WScript.Network
$drive = "F:"
$path = "\\Bar.foo.myCOmpany.com\logs"
if (test-path $drive) { $net.RemoveNetworkDrive($drive) }
$net.mapnetworkdrive($drive, $path, $true, $username, $password)
copy-item -path ".\foo.txt"  -destination "\\Bar.foo.myCOmpany.com\logs"
$net.RemoveNetworkDrive($drive)

}

Here's how you can run the function just change the parameters for username and password

Copy-FooItem -username "powershell-enth\vinith" -password "^5^868ashG"

Solution 2

I'd make use of BITS. Background Intelligent Transfer Service.

If BitsTransfer module not implemented for your session:

Import-Module BitsTransfer

Sample of using it to transfer a file using a credentials:

$cred = Get-Credential()
$sourcePath = \\server\example\file.txt
$destPath = C:\Local\Destination\
Start-BitsTransfer -Source $sourcePath -Destination $destPath -Credential $cred

Caveat: If you are executing script within a RemotePS session, then BITS is NOT supported.

Get-Help for Start-BitsTransfer:

SYNTAX

 Start-BitsTransfer [-Source] <string[]> [[-Destination] <string[]>] [-Asynchronous] [-Authentication <string>] [-Credential <PS
Credential>] [-Description <string>] [-DisplayName <string>] [-Priority <string>] [-ProxyAuthentication <string>] [-ProxyBypass
 <string[]>] [-ProxyCredential <PSCredential>] [-ProxyList <Uri[]>] [-ProxyUsage <string>] [-RetryInterval <int>] [-RetryTimeou
t <int>] [-Suspended] [-TransferType <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

More help...

Here is script to create $cred object so you aren't prompted for username/passwod:

    #create active credential object
    $Username = "user"
    $Password = ConvertTo-SecureString ‘pswd’ -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential $Username, $Password

Solution 3

You can try with:

copy-item -path .\foo.txt  -destination \remoteservername\logs -credential (get-credential)
Share:
10,534
vel
Author by

vel

Updated on July 16, 2022

Comments

  • vel
    vel almost 2 years

    I am a fresh beginner to PowerShell.

    I have username and password to reach a shared folder in a remote location.

    I need to copy the file foo.txt from the current location to \\Bar.foo.myCOmpany.com\logs within a PS1 script that is written for Powershell v3.0.

    How can I achieve this?