Search code examples
powershellportpowershell-remotingunc

PowerShell Copy-Item to remote - custom port


I want to copy some file from local computer to remote in a standard way:

Copy-Item -Path C:\some_path\test.txt -Destination \\server\c$\some_other_path\test.txt

Unfortunately i have to specify custom port due to routing on server. I am pretty new to remote management and powershell. Is there any way to specify port for Copy-Item or UNC path? If not, are they some other reasonable solutions to this problem? Thanks in advance.


Solution

  • Even though this is an old thread, I still provide my method here hoping that could help someone else.

    According to the official docs, there is no way to specify a port using Copy-Item, but you can try to use parameter ToSession to achieve your goal if your PS version is higher than 5, see the new features here.

    Create a session with a specified port:

    $session = New-PSSession -ComputerName $computer -Port $port
    

    Then copy files using the session:

    Copy-Item "C:\some_path\test.txt" -Destination "C:\some_other_path\test.txt" -ToSession $session
    

    And don’t forget to remove the session when you’re done.

    $session | Remove-PSSession
    

    Reference:
    Use PowerShell Copy-Item to File Transfer Over WinRM