Home > Back-end >  How do I execute ps script in XML
How do I execute ps script in XML

Time:10-17

I have one PS script that need to be execute/invoke via XML. getting error like

$sessions = Get-RDUserSession foreach($session in $sessions){Invoke- ...

Unexpected token 'in' in expression or statement. At line:1 char:78 $sessions = Get-RDUserSession foreach($session in $sessions){Invoke- ...
Missing closing ')' in expression. At line:1 char:109

config.xml

<Action name="KillAllUsers" Type="Powershell" Executor='$sessions = Get-RDUserSession
foreach ( $session in $sessions ) 
{ Invoke-RDUserLogoff -HostServer $session.HostServer -UnifiedSessionID $session.UnifiedSessionId -Force }'></Action>

CodePudding user response:

Line breaks in XML attributes are seemingly not preserved when you parse XML text into a DOM; they are replaced with spaces.

Therefore, whatever code you put in your Executor attribute ends up as a single line, which is why you must ;, PowerShell's statement separator, to separate your statements; note the ; after Get-RDUserSession and note that the line breaks are purely for readability here:

<Action name="KillAllUsers" Type="Powershell" Executor='
$sessions = Get-RDUserSession;
foreach ( $session in $sessions ) { 
  Invoke-RDUserLogoff -HostServer $session.HostServer -UnifiedSessionID $session.UnifiedSessionId -Force
}
'></Action>

As for the error you saw:

Due to your code being placed all on a single line without statement separators, the foreach statement syntactically became an argument to the Get-RDUserSession command, which caused a syntax error; a simple way to provoke the error is:

# -> ERROR: "Unexpected token 'in' in expression or statement."
Get-Date foreach ($i in 1..2) { $i }
  • Related