Home > Enterprise >  Using pipe in Windows PowerShell when scripting
Using pipe in Windows PowerShell when scripting

Time:12-31

I need to create scripts that manipulate files and their contents. If I use Windows Powershell, the following command perfectly works:

(Get-Content my_file.txt).Replace("aaa","bbb") | Set-Content my_file.txt

This command will replace any occurence of aaa by bbb. Yet, I would like to wrap this into a script file that I named rename.cmd. The content of the file is

CMD (Get-Content my_file.txt).Replace("aaa","bbb") | Set-Content my_file.txt

Now, if I type .\rename.cmd in PowerShell, I get the following error:

PS C:\Users\me\> .\rename.cmd
'Set-Content' is not recognized as an internal or external command,
operable program or batch file.

CodePudding user response:

A 'CMD' file is for CMD scripts (/the WinNT extension of 'BAT'/Batch files/scripts) - run by 'Cmd.exe' (/previously by 'Command.com' in the distant DOS past).

You need to change your script to have a 'PS1' file extension, so it's named 'Rename.ps1' instead - so it will be run by the correct interpreter/shell - 'PowerShell.exe'.

(But then you might then reach the point of wanting to declare/pass-in arguments to your script.)

  • Related