Page 1 of 1

escaping powershell in batch loop

Posted: 25 Jul 2023 10:33
by lazna
have following loop

Code: Select all

for /f "tokens=1-3 delims=- " %%a in ('
			powershell.exe -Command "Get-EventLog -ErrorAction SilentlyContinue -Newest 1 -LogName System -EntryType Error -Source Tcpip | ForEach-Object { \"$(Get-Date $_.TimeGenerated) - $($_.ReplacementStrings -join '#')\" }; Write-output ^$error[0]"
			') do (
			echo %%a %%b %%c
			)
but got error

Code: Select all

- was unexpected at this time.
On command line, powershell command work fine. Trying to escape some dashes and semicolon, but have no luck. What could cause this error?

Re: escaping powershell in batch loop

Posted: 31 Jul 2023 22:01
by Squashman
Remember you are using a batch file. So any special characters need to be escaped. The closing parentheses thinks you are closing the FOR argument so it thinks the hyphen is a command. You need to escape them.

Code: Select all

for /f "usebackq tokens=1-3 delims=- " %%a in (`
powershell.exe -Command "Get-EventLog -ErrorAction SilentlyContinue -Newest 1 -LogName System -EntryType Error -Source Tcpip | ForEach-Object { \"$(Get-Date $_.TimeGenerated^) - $($_.ReplacementStrings -join '#'^)\" }; Write-output ^$error[0]"
`) do (
echo %%a %%b %%c
)