Powershell command not working
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Kojiro Saito
2017-7-15
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 个评论
Kojiro Saito
2018-6-11
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
2023-4-5
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.
更多回答(1 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!