Powershell command not working
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
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
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
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.
Plus de réponses (1)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!