New-Item on remote system

Mark Verhunce 41 Reputation points
2022-01-27T19:01:13.28+00:00

I am trying to test if a directory exists on a remote system and if not create it and then copy a file from a server to the remote system.

When I run the following code it does not create the folder on the remote system, and thus not copying the file. If I change $SourcePath to "\Server*", everything from this path is copied as expected. Any Ideas?

$Session = New-PSSession -ComputerName "TestComputer"
$SourcePath = "\Server\testapp.exe"
$DestinationPath = "C:\Software\TestAPP\"
If(!(Test-Path $DestinationPath)) {New-Item -ItemType Directory -Force -Path $DestinationPath}
Copy-Item -Path $SourcePath -ToSession $Session -Destination $DestinationPath -Force

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,575 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 47,386 Reputation points
    2022-01-27T19:56:02.56+00:00

    You create a PowerShell session at the beginning of your script. But you never ENTER the session. Your Test-Path is checking the LOCAL machine and your New-Item will create the directory on the LOCAL machine.

    The Copy-Item uses the UNC name in the $SourcePath and copies the item to the location found in the $DestinationPath on the machine in your $Session variable ("TestComputer") -- but you're running the Copy-Item on YOUR LOCAL machine, not the remote machine.

    0 comments No comments

  2. Limitless Technology 39,701 Reputation points
    2022-01-28T18:02:18.543+00:00

    Hello @Mark Verhunce

    You cant use a filename reference as a path variable. That is why a wildcard for the folder will work.
    For copying independent file objects you can use either $Files = "file.name" or in a more complex way combine the usage of Get-ChildItem from $Sourcepath and then Select what you need.

    Hope this helps with your query,

    ------------

    --If the reply is helpful, please Upvote and Accept as answer--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.