New-Item in PowerShell is not working when using a file in the source path

Mark Verhunce 41 Reputation points

I am trying to copy a file from a server to a remote system with the code below. I want to check if the path exists and if not create the folder. When I run this the folder does not get create on the server, thus the file does not either. However, if $SourcePath = "\Server\Software*", the fold C:\Software\Software Title is created and all of the files located in "\Server\Software\" are copied to the remote system. Also, if the path "C:\Software\Software Title" exists on the remote computer, file.exe is copied to the remote system.

I am wondering why the folder C:\Software\Software Title is not created when I only want to copy one file? Any help would be appreciated.

$Session = New-PSSession -ComputerName "TestComputer"
$SourcePath = "\Server\Sofware\file.exe"
$DestinationPath = "C:\Software\Software Title\"
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,436 questions
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 32,531 Reputation points

    Test-Path does not have a -ToSession switch so you need to put that portion of the code in an Invoke-Command to get it to create the folder on TestComputer. Otherwise you're referencing the C drive of the machine where the script is running.

    Note that I did not test your code.