Powershell command not working

12 vues (au cours des 30 derniers jours)
Umberto
Umberto le 14 Juil 2017
Commenté : Robert Heaton le 5 Avr 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

Réponse acceptée

Kojiro Saito
Kojiro Saito le 15 Juil 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 commentaires
Kojiro Saito
Kojiro Saito le 11 Juin 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 le 5 Avr 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.

Connectez-vous pour commenter.

Plus de réponses (1)

Umberto
Umberto le 17 Juil 2017
It works! Thank you very much (:

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by