ShellGames
ShellGames

Reputation: 87

How to copy files in powershell that contain variable in name?

I am trying to copy files that match an environment identifier set to a variable. The output of the command looks good until in include the where-object section. I only want to copy files that contain the string in the $environmenttype string.

What do I need to change to get the where-object to operate correctly?

$environmenttype = "dev"
Write-Output "environmenttype is set to $environmenttype"
Get-ChildItem -path "\content" | Select-Object -ExpandProperty name | Where-Object {$_ -contains "$environmenttype"} | Copy-Item -Path "C:\newdir"

Upvotes: 2

Views: 230

Answers (2)

Venkataraman R
Venkataraman R

Reputation: 12959

You can use match predicate, which supports variable usage.

$filter = "ansi" 
Get-ChildItem -path "c:\dev\" | Where-Object {$_.Name -match "$filter"} | Copy-Item -Destination C:\dev\testFolder

Upvotes: 1

marsze
marsze

Reputation: 17035

How I'd write it:

Get-ChildItem "\content" -File | where BaseName -like "*$environmenttype*" | Copy-Item "C:\newdir"

I am using the simplified version of Where-Object and the -like operator/parameter and a wildcard pattern (note the asterisks *).

BaseName is the name of the file without extension.

I omitted some implicit parameter names, and added the -File switch to include files only.

(Note that the path in Copy-Item is set by the pipeline, so the parameter is actually -Destination)

Upvotes: 1

Related Questions