powershell

PowerShell Copy-Item: how to copy only folder contents if source path requires -literalPath


As part of a larger script, I'm trying to get PowerShell to copy the contents of a specified folder into another directory. The problem I'm having is that I need to use -LiteralPath as this script will ultimately be used to copy the contents of various folders, many of which include the problematic EmDash. As such, my code at the moment looks something like this:

Copy-Item -LiteralPath "C:\Example – Path\SourcePath" -Destination "C:\DestinationPath" -Recurse -Force

However, using -LiteralPath prevents me from being able to append wildcards to the path. So I can't just have

C:\Example – Path\SourcePath\*

to specify that I only want the contents of the source folder copied, rather than the entire directory.

Being a rookie with creating scripts, I've been relying on Chat-GPT for assistance and it has provided an alternative solution where I define a custom function that performs the copy procedure as needed. But I'm just wondering if there's something cleaner / simpler which will obviate the need for a new function.

Any thoughts or suggestions much appreciated.


Solution

  • Therefore, use -Path, not -LiteralPath:

    Copy-Item -Path "C:\Example – Path\SourcePath\*" -Destination "C:\DestinationPath" -Recurse -Force
    

    Note: