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.
The purpose of the -LiteralPath
parameter of PowerShell cmdlets is to interpret its argument(s) literally, a.k.a verbatim.
By contrast, the purpose of the -Path
parameter is to interpret its argument(s) as wildcard patterns, such as 'C:\Example – Path\SourcePath\*'
Therefore, use -Path
, not -LiteralPath
:
Copy-Item -Path "C:\Example – Path\SourcePath\*" -Destination "C:\DestinationPath" -Recurse -Force
Note:
In PowerShell provider cmdlets such as Copy-Item
, -Path
is the (first) positional parameter, so that you may omit -Path
in the command above.
Conversely, this means: In order to ensure that file path argument(s) are interpreted literally (verbatim), you must use -LiteralPath
or, in PowerShell (Core) 7+ its -lp
alias.
While the distinction between -Path
and -LiteralPath
typically doesn't matter, it does with paths that happen to contain [
and ]
, as these characters are metacharacters in PowerShell wildcard patterns.
Your specific path contains a non-ASCII-range character, –
(EN DASH, U+2013
), which looks like, but isn't the same as the ASCII-range -
character (HYPHEN-MINUS, U+002D
)
As long as PowerShell interprets your script file correctly, that isn't a problem.
However, if your script file is UTF-8 encoded, but lacks a BOM (byte-order mark), Windows PowerShell will misinterpret it.