Copy / transfer a file using PowerShell 2.0

I am trying to create a PowerShell script to copy a file from my local computer to a remote computer using its IP address.

I tested my client-server connection using the following command:

Invoke Command -ComputerName <IP Address> -ScriptBlock {ipconfig} -Credential $credential 

(where $ credential was entered immediately before this command).

I tried using Copy-Element and Robocopy , but I don’t understand if it will accept my credentials, and then allow me to copy the file from local to the remote machine. To be specific, can they support local remote file transfers ?

Many times I came across errors such as: Bad username and password, source path does not exist or destination path does not exist. But I still wanted to be sure that I was on the right track and used the right commands to implement what I want, or if there is anything else that I should consider. How can I fix this problem?

+6
source share
2 answers

It looks like you are trying to copy a file using PowerShell remote access. As stated in other answers, it would be easier to use Copy-Item and / or Robocopy to copy from source to share on the destination computer.

If you want to copy a file using PowerShell remote access, you can split the file into a variable and use it in a remote script block. Sort of:

 $contents = [IO.File]::ReadAllBytes( $localPath ) Invoke-Command -ComputerName <IP Address> ` -Credential $credential ` -ScriptBlock { [IO.File]::WriteAllBytes( 'C:\remotepath', $using:contents ) } 

Of course, if the file you are reading is really large, it can cause the remote connection to end due to out of memory (by default, PowerShell limits remote connections to about 128 MB).

If you are stuck with PowerShell 2, you need to pass bytes as a parameter to the script block:

 $contents = [IO.File]::ReadAllBytes( $localPath ) Invoke-Command -ComputerName <IP Address> ` -Credential $credential ` -ScriptBlock { param( [byte[]] $Contents ) [IO.File]::WriteAllBytes( 'C:\remotepath', $Contents) } ` -ArgumentList @( ,$contents ) 

And yes, you must wrap $contents in an array, passing it as a value to the -ArgumentList parameter, and it must be prefixed with a comma operator, otherwise your remote script block will only receive the first byte.

+7
source

One of the nice things about PowerShell (unlike DOS) is that it supports UNC paths. Thus, you can only literary:

 Copy-Item -Path <local file path> -Destination \\<server IP>\<share>\<path> 

Of course, your account will need to have access to this location. If you need to enter alternative credentials, you can pre-authenticate with net use \\<server IP>\<share> /user:[<domain>\]<user> <password>

+6
source

Source: https://habr.com/ru/post/948956/


All Articles