I am trying to get SQL to execute some powershell commands using xp_cmdshell which has been working, however I'm running into an unusual problem. When I try to use a pipeline, it doesn't recognize the command after the pipeline. I tried this from the standard cmd line and can confirm that the same issue happens. This is the command I'm using:
powershell.exe -command get-eventlog -Newest 10 -LogName Application -Before "2018-04-18T22:02:23" -After "2018-04-17T22:02:23" -computername dk01sv1115 | Select Message
When I use the command without using | Select Message
at the end, it works without issue. The issue is I'm not getting the full event message I've tried using Select and Format functions to try to get the full details but the pipe appears to be the issue. If you run the same command after starting powershell (IE run powershell.exe then run the command) it works without issue, however when you use SQL to run powershell.exe as a seperate line in SQL it runs indefinitely. EXAMPLE SQL:
Declare @command nvarchar(1000),@computername nvarchar(1000)
Set @computername = 'test'
Set @command = 'powershell.exe
get-eventlog -Newest 10 -LogName Application -Before "' + REPLACE(Convert(VARCHAR(255),GETDATE(),120),' ','T') +'" -After "' + REPLACE(Convert(varchar(255),DateAdd(dd,-1,GETDATE()),120),' ','T') + '" -computername ' + @computername + '
exit'
exec xp_cmdshell @command