我想在没有 WINRM 的情况下将文件从本地服务器复制到远程服务器。远程服务器已获得凭据,但不在本地网络或本地服务器的本地域中。 请问您有解决办法吗?
I have this error:
MethodInvocationException: D:\powershell\ip.ps1:23:1
Line |
23 | $WebClient.DownloadFile($Source, $Dest)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
Here is my code:
$Source = "C:\test10\test10.txt"
$Dest = "\\public_ipadress_server\C:\test11\test10.txt"
$Username = "administrator"
$Password= convertto-securestring -AsPlainText -Force -String password
$MyIP = (Invoke-WebRequest -uri "http://ifconfig.me/ip").Content
$MyIP | Out-File $Source
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$WebClient.DownloadFile($Source, $Dest)
答案 0 :(得分:2)
是否可以使用标准的 UNC 网络副本?我会考虑将驱动器映射到远程 PC 上的共享。 net use 命令将允许您执行此操作,输入远程计算机的凭据。然后您可以通过映射的驱动器复制文件。我还添加了一些代码,以更安全的方式提供凭据。以明文形式存储密码不是很好的做法,这似乎是您正在做的。
$source = "C:\test10\test10.txt"
$desiredMappedDrive = "J"
$desiredMappedDrivePath = "\\public_ipadress_server\C$" # Map to administrative C: drive share requires administrator credentials)
$destination = "${desiredMappedDrive}:\test11\test10.txt"
$passwordFile = "C:\temp\encryptedCred"
if (-not (Test-Path $passwordFile) ) {
$cred = Get-Credential
} else {
$fileContents = Get-Content $passwordFile
$userEncryptedString = $fileContents[0]
$passEncryptedString = $fileContents[1]
$userSecureString = $userEncryptedString | ConvertTo-SecureString
$passSecureString = $passEncryptedString | ConvertTo-SecureString
# convert secure string back to text
$userString = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto( [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($userSecureString) )
$cred = [pscredential]::new($userString, $passSecureString)
}
if ($cred) {
$response = net use ${desiredMappedDrive}: $desiredMappedDrivePath /USER:$($cred.UserName) $($cred.GetNetworkCredential().Password)
$response
if ($response -match "command completed successfully") {
$cred.UserName | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File $passwordFile
$cred.Password |ConvertFrom-SecureString | Out-File -Append $passwordFile
Write-Host "Credentials have been saved to $passwordFile. While file exists you will not be asked to enter credentials for future script executions"
}
Copy-Item $source -Destination $destination
}