Just looking to see if anyone knows of a way to shorten this powershell line:

gci -Recurse -path $temp | ? {(".jpg",".png" -eq $_.extension -and $_ -match 'this' -and $_ -match "that")} | mi -Destination ($Images) -Force

The line is in this code:

$Temp = "F:\Temp-Images"
$Images = "F:\Images\"
gci -Recurse -path $Temp | ? {(".jpg",".png" -eq $_.extension -and $_ -match 'this' -and $_ -match "that")} | mi -Destination ($Images) -Force

The script is meant to look in a folder ($Temp), find any files with the extension .jpg or .png, AND that have both the words "this" and "that" in the filename. If it finds a match, it moves the file to the destination folder ($Images)

So if there's a file in "F:\Temp-Images" named "this-that.png", it will get moved to "F:\Images\"

I'm new to PowerShell, so I pieced the above code together via google searches. I don't know if my syntax is great or not, but it's working for me. I'm just wondering if there's a way to shorten the code. For example, is there a way to shorten this?:

-and $_ -match 'this' -and $_ -match "that"


  • Which PowerShell version, is there an order in this and that? – LotPings Aug 31 '17 at 22:02

Shorting as much as possible get's cryptic ;-)

$Temp = "F:\Temp-Images\"
$Images = "F:\Images\"
ls $Temp -R -I *.jpg,*.png|?{$_.Name -match 'this.*that|that.*this'}|mi -D ($Images) -Fo

To test I'd append -WhatIf or -Confirm to Move-Item

  • Wow, that is cryptic! :) But very cool. I've give it a try. Thanks!! Question this part: 'this.*that|that.*this' - Is it repeated in reverse because it's sensitive to the order of the words? – D. Hill Aug 31 '17 at 22:24
  • This is a Regular Expression (as always with -match) the vertical bar here means or so the order doesn't matter .* matches anything in between. – LotPings Aug 31 '17 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.