Command not working in bat script but works in CLI

0 votes
Powershell -Command "cat .\tmp.txt | %{$_ -replace '\D', ''}"

I'm trying to run the above command in a batch script. It works perfectly fine if I run it on command line but this shows up if I try and run it from the script:

    Expressions are only allowed as the first element of a pipeline.
    At line:1 char:39
+ cat .\tmp.txt | {$_ -replace '\D', ''} <<<<
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
Jul 19, 2018 in Other DevOps Questions by shubham
• 7,340 points

recategorized Nov 12, 2018 by Priyaj 1,392 views

1 answer to this question.

0 votes
powershell /?

If you run the above command this help text will show

To write a string that runs a Windows PowerShell command, use the format:
    "& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.

Therefore you need to make the following changes in your batch file

powershell -Command "&{ cat .\tmp.txt | ForEach-Object {$_ -replace '\D', ''} }"

(note the extra curly braces wrapped around your command and % being replaced with ForEach-Object)

answered Jul 19, 2018 by ajs3033
• 7,300 points

Related Questions In Other DevOps Questions

0 votes
0 answers
0 votes
1 answer

How to stop sqlplus command in unix shell script when any sql fails

One idea would be to launch the ...READ MORE

answered Jul 16, 2018 in Other DevOps Questions by Kalgi
• 52,360 points
0 votes
1 answer

Using conditional to execute a command in salt

You can use unless inside your state ...READ MORE

answered Jul 23, 2018 in Other DevOps Questions by DareDev
• 6,890 points
0 votes
0 answers

How to use version name in Bamboo script

Hi All, We have 3 tasks in our ...READ MORE

Apr 9, 2020 in Other DevOps Questions by Abhishek
• 280 points
+15 votes
2 answers

Git management technique when there are multiple customers and need multiple customization?

Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE

answered Mar 27, 2018 in DevOps & Agile by DragonLord999
• 8,450 points
+2 votes
1 answer
0 votes
1 answer

Execute puma workers only in prod but not in dev environment

You can us RACK_ENV here instead of ...READ MORE

answered Aug 16, 2018 in Other DevOps Questions by ajs3033
• 7,300 points
0 votes
1 answer

Puppet not recieving hiera data

Puppet does not consider the variables defined ...READ MORE

answered May 7, 2018 in Other DevOps Questions by ajs3033
• 7,300 points
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP