0

I am trying to copy files with names that fulfills a given set of criteria from one folder to another. From this answer, I found that the -Include statement could be used for this.

My issue is that I need the criteria to be user-specified (through a variable), with the possibility of containing multiple criteria. That is, I try to do the following:

# THIS WORKS FINE
$includeFiles = "*tests.jar"
Copy-Item "from/path" "to/path" -Include $includeFiles 

# THIS RETURNS NOTHING
$includeFiles = "*tests.jar, other.jar"
Copy-Item "from/path" "to/path" -Include $includeFiles 

How do I work around this issue? Is it somehow possible to "destring" the variable, use another syntax or similar?

Tormod Haugene
  • 3,538
  • 2
  • 29
  • 47

1 Answers1

2
# THIS WORKS FINE
$copyPattern = "*tests.jar", "other.jar"
Copy-Item "from/path" "to/path" -Include $copyPattern

The point is that the argument to -Include is an array of strings, each string is a pattern to include. The way you wrote it would require a comma and space in the file name. So, unless you have such files, nothing would be included.

If you are positive that the pattern will never include commas and you'd rather just have a single string, you can of course convert it to an array:

$copyPatterns = "*tests.jar, other.jar" -split ', '

Note that parsing works differently in arguments to commands, which is why the following does work as well:

Copy-Item from/path to/path -Include *tests.jar,other.jar
Joey
  • 344,408
  • 85
  • 689
  • 683
  • Great answer! In my scenario, the input variable has to be a single string, but splitting that string before using it to Include works great. Thanks! – Tormod Haugene Jul 28 '17 at 10:21