Powershell command not working

13 Ansichten (letzte 30 Tage)
Umberto
Umberto am 14 Jul. 2017
Kommentiert: Robert Heaton am 5 Apr. 2023
Hello everyone,
I'm writing a script where I call a powershell cmdlet
'powershell.exe -inputformat none cat old_file.txt | % {$_ -replace "old_string","new_string"} > new_file.txt'
But I get the error '% is not recognized as an internal or external command, operable program or batch file'.
When I call other simple powershell lines I do not get the same issue so I guess it's not a problem concerning PowerShell path. Also, if I substitute % with char(27) the problem is not solved. The same using % alias ForEach-Object.
Do you have any suggestion on how to fix it?
Thank you in advance

Akzeptierte Antwort

Kojiro Saito
Kojiro Saito am 15 Jul. 2017
I could get correct results by using the following command instead of % character.
command = 'powershell.exe -inputformat none -Command "(gc old_file.txt) -replace ''old_string'', ''new_string'' | sc new_file.txt"';
[res, stat] = system(command);
Does this work for you?
  3 Kommentare
Kojiro Saito
Kojiro Saito am 11 Jun. 2018
Add double quote to the Power Shell command. The following will work.
!powershell "Get-Content oldfile.txt | Where {($_.ReadCount % 1000) -eq 0} | Set-Content newfile.txt"
Robert Heaton
Robert Heaton am 5 Apr. 2023
I had a similar problem with a PowerShell command entered through Matlab system() function. After digging a bit into this, it seems the cause is that the supplied string is intrepreted by the standard shell and not the PowerShell. As I understand it, the first command (cat) is handled by the PowerShell, but the pipe and commands after it are interpreted by the standard DOS shell which does not have the same command structures. In order to use a pipe in this way, I found I had to use an escape character for the pipe, replacing the | with ^| to get it to work. No idea why the caret is the appropriate escape character -- I also had to escape the double quotes within the Matlab character array for parameter arguements containing spaces using \". Surrounding the entire string in double quotes achieves the same thing by ensuring the entire sequence if processed by the PowerShell, but I'm unclear of how to structure this within a string already containing double quotes.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Umberto
Umberto am 17 Jul. 2017
It works! Thank you very much (:

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by