I am starting several powershell instances from a batch script.
With one, I'd like to tail a file and add a timestamp to each line. The command itself works well in powershell directly:
filter timestamp {"$(Get-Date -Format G): $_"}; Get-Content .\MyLog.txt -tail 10 -wait | Select-String 'Search term' | timestamp
But when I use the following command within cmd, I get errors:
start powershell -Command "filter timestamp {"$(Get-Date -Format G): $_"}; Get-Content .\MyLog.txt -tail 10 -wait | Select-String 'Search term' | timestamp"; pause
In Zeile:1 Zeichen:18
start powershell -Command "filter timestamp {"$(Get-Date -Format G): ...
~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
I wonder if I need to escape? Have tried many options but after hours I need some pro help.
Thanks a lot.
CodePudding user response:
In Powershell, there are several ways to include a double-quote character in a string that is between double-quotes (i.e `"). That's the problem with your command line, when started from a CMD prompt.
To solve your issue, use """ in the -Command string instead of " (except of course for the start and end of your command). See below:
start powershell -Command "filter timestamp {"""$(Get-Date -Format G): $_"""}; Get-Content .\MyLog.txt -tail 10 -wait | Select-String 'Search term' | timestamp"; pause
Also, instead of adding the pause at the end of your command, you can use the -NoExit switch from powershell.exe:
start powershell -NoExit -Command "filter timestamp {"""$(Get-Date -Format G): $_"""}; Get-Content .\MyLog.txt -tail 10 -wait | Select-String 'Search term' | timestamp"
