I wrote a script to remove .vb code files when there are corresponding .cs files in a certain directory structure. But I felt like there were some extra statements that I had to put in there that didn't feel natural. Is there a better way to do this check and then action?

Specifically, having to do the foreach at the end didn't seem right to me. I also didn't know if there was a more PowerShell-y way to do the change extension and test-path.

ls . -include *.vb -recurse 
    | ? { $cs = [System.IO.Path]::ChangeExtension($_.FullName, ".cs"); Test-Path $cs } 
    | % { rm $_ -force }

1 Answer 1


You could combine expression vs. command mode in PowerShell, process only files (!$_.PSIsContainer) and use regex instead of ChangeExtension:

gci -include *.vb -Recurse |
    ? { (!$_.PSIsContainer) -and (Test-Path ($_.FullName -replace "\.vb$", ".cs") } |
    % { rm $_ -force } 
  • \$\begingroup\$ That's a big one, I couldn't figure out why I needed the temporary $cs variable; just wrapping it in parens fixes it from encountering "parameter cannot be found that accepts argument 'System.Object[]'" (and makes sense now that I look though that article and see the fix). Thanks! \$\endgroup\$
    – bdukes
    Aug 7, 2012 at 17:05
  • 1
    \$\begingroup\$ And it looks like I don't need to specify $_.FullPath, but can just use $_ (with either the ChangeExtension or -replace method) \$\endgroup\$
    – bdukes
    Aug 7, 2012 at 17:07
  • \$\begingroup\$ It doesn't look like gci *.vb -recurse actually recurses. I think I have to specify current directory as the path, then *.vb as the filter for recursing to work correctly. \$\endgroup\$
    – bdukes
    Aug 7, 2012 at 17:11
  • \$\begingroup\$ you are right: gci -include *.vb -Recurse — works much better \$\endgroup\$
    – Akim
    Aug 7, 2012 at 17:13
  • \$\begingroup\$ Actually, removing FullPath breaks it once you get into the deeper folders, since you're only getting the name by default, not the full path. \$\endgroup\$
    – bdukes
    Aug 7, 2012 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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