2012-11-05 84 views
3

我是PowerShell的新手入门者。如何使用PowerShell凭证从本地复制到远程位置?

我有用户名和密码到达远程位置的共享文件夹。

我需要到文件foo.txt从当前位置复制到\\Bar.foo.myCOmpany.com\logs是为PowerShell的3.0写的PS1脚本中。

我该如何做到这一点?

+0

远程位置是网络共享还是ftp文件夹? –

+0

网络;不是ftp – pencilCake

回答

4

Copy-Item不支持-credential参数,这样做的参数ameter出现 ,但它不是在任何Windows PowerShell的核心cmdlet或提供”

你可以试试下面的函数映射网络驱动器和调用拷贝支持

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) 

} 

下面是你可以运行功能更改用户名和密码的参数

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

我是否需要在连接目标服务器之前和/或之后关闭连接?当我浏览网页时,我发现它是必需的吗? – pencilCake

+0

是的,你可以做到这一点?我的解决方案是否适合你? – PowerShell

+0

无论如何,我在尝试此操作时遇到错误: rrorMessage:FileSystem提供程序仅在New-PSDrive cmdlet上支持凭据。在没有指定凭证的情况下再次执行操作..Exception.Message 在行:1 char:1 – pencilCake

1

你可以尝试:

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

但是我在哪里传递用户名和密码? – pencilCake

+0

'get-credential'打开输入用户名和密码的窗口。你需要从文件中读取它们吗? –

+0

是的,它会成为一个自动化副本的一部分 – pencilCake

4

我会充分利用BITS的。后台智能传输服务。

如果BitsTransfer模块不是你的会话来实现:

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

买者

Import-Module BitsTransfer 

使用它使用凭证传输文件的样品如果你内的执行脚本RemotePS会话,则BITS是不支持

获取帮助的启动BitsTransfer:

语法

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>] 

更多的帮助...

这里是脚本来创建$趋之若鹜的对象,所以你不会提示输入用户名/ passwod:

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