eko forever
eko forever

Reputation: 13

PowerShell Error - Scheduled Task - expression expected

I am setting up scheduled tasks for logging off disconnected sessions. I setup the task with the action of opening PowerShell.exe with the argument shown below

powershell.exe -ExecutionPolicy Bypass -NoProfile -command "Invoke-command -ScriptBlock {quser | Select-String "Disc" | ForEach {logoff ($_.tostring() -split " +")[2]}}"

The argument works by itself in PowerShell but when I try to create this task it fails with the error:

powershell.exe : At line:1 char:89
At line:2 char:1
+ powershell.exe -ExecutionPolicy Bypass -NoProfile -command "Invoke-co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (At line:1 char:89:String) [], RemoteException

    + FullyQualifiedErrorId : NativeCommandError
+ ...  {quser | Select-String  Disc | ForEach {logoff (((.tostring() -split ...
+                                                                  ~
An expression was expected after '('.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedExpression

I believe that I need to have the expression evaluated for the string to populate correctly and have tried escaping both quotes and parentheses to try to get it to work. Any help would be greatly appreciated.

Upvotes: 1

Views: 914

Answers (1)

marsze
marsze

Reputation: 17084

Your problem are probably the quotes. Mind you have to properly quote and escape your command line arguments. You can use single quotes inside your command for simplicity, or skip them alltogether if not needed. Also, the Invoke-Command is redundant.

Try this:

powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "quser | Select-String Disc | foreach {logoff ($_.Line -split ' +')[2]}"

Upvotes: 2

Related Questions