I am writing a powershell script that copies a .jar file from a server to a remote VM. When it gets to the Copy-Item command, it fails with this error:
Copy-Item : The user name or password is incorrect.
Copy-Item -Path $source -Destination '\\consolidate\c$ ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Comma
nds.CopyItemCommand
I have tried adding a -Credentials argument to the Copy-Item command. That gives me this error:
The FileSystem provider supports credentials only on the New-PSDrive cmdlet.
Perform the operation again without specifying credentials.
At [file path]
Copy-Item -Path $source -Destination '\\consolidate\c$ ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
FullyQualifiedErrorId : NotSupported
Here is the code around the line in question:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
Invoke-Command -ComputerName "consolidate" -Credential $credentials -ScriptBlock {
New-PSDrive -Name "X" -PSProvider FileSystem -Root "C:\" -Credential $Using:credentials
}
Copy-Item -Path $calcEngineJarPath -Destination '\\consolidate\c$'
...
Remove-PSDrive X
CodePudding user response:
You'd want to create a new PSDrive on your local machine that maps the network path to a drive letter:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
# Create mapped network drive
New-PSDrive -Name "X" -PSProvider FileSystem -Root "\\consolidate\c$\" -Credential $credentials
# Copy to mapped network drive
Copy-Item -Path $calcEngineJarPath -Destination X:\
Alternatively, use Copy-Item
's -ToSession
parameter:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
# Create a new PSRemoting session on the target machine using the credentials
$session = New-PSSession -ComputerName consolidate -Credentials $credentials
# Copy file to remote session drive
Copy-Item -Path $calcEngineJarPath -Destination C:\ -ToSession $session