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

ⅰ亾dé卋堺 提交于 2020-01-04 05:23:27

问题


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?


回答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"



回答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



回答3:


You can try with:

copy-item -path .\foo.txt  -destination \remoteservername\logs -credential (get-credential)


来源:https://stackoverflow.com/questions/13239377/how-can-i-copy-from-local-to-a-remote-location-with-credentials-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!