Powershell command not working

13 visualizaciones (últimos 30 días)
Umberto
Umberto el 14 de Jul. de 2017
Comentada: Robert Heaton el 5 de Abr. de 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

Respuesta aceptada

Kojiro Saito
Kojiro Saito el 15 de Jul. de 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 comentarios
Kojiro Saito
Kojiro Saito el 11 de Jun. de 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 el 5 de Abr. de 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.

Iniciar sesión para comentar.

Más respuestas (1)

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

Categorías

Más información sobre Mathematics en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by