escaping powershell in batch loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
lazna
Posts: 54
Joined: 27 Dec 2012 10:54

escaping powershell in batch loop

#1 Post by lazna » 25 Jul 2023 10:33

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?

Squashman
Expert
Posts: 4471
Joined: 23 Dec 2011 13:59

Re: escaping powershell in batch loop

#2 Post by Squashman » 31 Jul 2023 22:01

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
)

Post Reply