4

I want to use powershell's 'replace' in some long cmd.exe pipeline; how can I redirect from cmd to powershell input? The line below doesn't work, gives empty output:

c:\>(echo foo && echo bar) | powershell -Command "%{$_ -replace \"f\",\"x\"}"
4

Based on some further googling results, adding $input | to powershell command seems to work, i.e.:

C:\>(echo foo && echo bar) | powershell -Command "$input | %{$_ -replace \"f\",\"x\"}"
xoo
bar

(note: when used in a .bat file, the % above needs to be replaced with %%, apparently)

  • 1) In CMD you should use & to string the execution of multiple statements, or may use carriage returns if the statements are wrapped in Parenthesis. && will cause CMD to do an unnecessary (in this example) evaluation on the first statement, and will only execute the following statement if the first was successful. – Ben Personick Jan 4 at 21:09
  • 2.a) In CMD we want to leverage for loops wherever possible because the scripting language is non Object oriented, However In PS it's preferable to act on the Object directly wherever possible since the language is OO. – Ben Personick Jan 4 at 21:12
  • 2.b) In your example the Loop provides no function and should be removed. – Ben Personick Jan 4 at 21:13
  • 1
    3) The resulting code could simply be: (echo foo & echo barf) | powershell -Command "$input -replace \"f\",\"x\"" – Ben Personick Jan 4 at 21:14

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.