从本地复制文件复制项目使用凭据删除服务器

我想从本地机器上复制一些文件和文件夹到远程服务器:

Copy-Item .\copy_test.txt -destination "\\serverip\c$\backups\" 

但我得到一个错误:

 复制项目:login失败:未知的用户名或错误的密码。
在线:1 char:10
 + Copy-Item <<<<。\ copy_test.txt -destination“\\ serverip \ c $ \ backups \”-verbose
     + CategoryInfo:NotSpecified:(:) [Copy-Item],IOException
     + FullyQualifiedErrorId:System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand 

我试图使用凭据,但是这个命令不允许-Credential参数。 我search了很多,在每个例子中,只要执行Copy-Item $source -destination $destination ,命令都非常简单,我想知道为什么在我的工作站中这么辛苦。

创build新的PSDrive

我试图创build一个New-PSDrive但没有奏效。

 $creds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username, $password New-PSDrive -Name X -PSProvider FileSystem -Root '\\$serverip\c$' -Credential $creds -Persist Copy-Item '.\copy_test.txt' -Destination 'X:\backups' Remove-PSDrive -Name X 

这是错误信息:

  PS C:\ Users \ Administrator \ Desktop>。\ copyfiles.ps1
新PSDrive:没有findnetworkingpath
在C:\ Users \ Administrator \ Desktop \ copyfiles.ps1:11 char:1
 +新PSDrive  - 名称X -PSProvider文件系统-Root'\\ $ serverip \ c $'-Credential $ c ...
 +〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo:InvalidOperation:(X:PSDriveInfo)[New-PSDrive],Win32Exception
     + FullyQualifiedErrorId:CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveC

复制项目:找不到驱动器。 名称为“X”的驱动器不存在。
在C:\ Users \ Administrator \ Desktop \ copyfiles.ps1:12 char:1
 + Copy-Item'。\ copy_test.txt'-Destination'X:\ backups'
 +〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜 ~~~~
     + CategoryInfo:ObjectNotFound:(X:String)[Copy-Item],DriveNotFoundException
     + FullyQualifiedErrorId:DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

删除PSDrive:找不到驱动器。 名称为“X”的驱动器不存在。
在C:\ Users \ Administrator \ Desktop \ copyfiles.ps1中:13 char:1
 +删除PSDrive -Name X
 + ~~~~~~~~~~~~
     + CategoryInfo:ObjectNotFound:(X:String)[Remove-PSDrive],DriveNotFoundExcepti
     + FullyQualifiedErrorId:DriveNotFound,Microsoft.PowerShell.Commands.RemovePSDriveCommand 

我的服务器

我的服务器是AWS中的Windows实例。 我有正确的权限,因为我能够运行其他命令,如Invoke-Command为了检查一些服务到远程服务器。

  PS> $ PSVersionTable.PSVersion

主要次要版本修订
 ----- ----- ----- --------
 4 0 -1 -1 

如果需要凭据访问远程共享,则需要将其映射到(PS)驱动器,然后才能将其与其他cmdlet一起使用。

 $cred = Get-Credential New-PSDrive -Name X -PSProvider FileSystem -Root "\\$serverip\c$" -Credential $cred -Persist Copy-Item '.\copy_test.txt' -Destination 'X:\backups' Remove-PSDrive -Name X 

我找到了解决方案。 我正在使用PowerShell版本4.0,然后将我的版本升级到5.0

在以前的版本中, Copy-Item不允许凭证。 现在可以通过服务器之间的会话复制文件:

 $deploy_dest = "C:\backup" $username = "$server\Administrator" $password = Get-Content C:\mypassword.txt | ConvertTo-SecureString -AsPlainText -Force $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password $session = New-PSSession -ComputerName $server -Credential $creds Copy-Item -Path .\copy_test.txt -Destination -ToSession $session