PowerShell 错误 - 计划任务 - 需要表达式

PowerShell Error - Scheduled Task - expression expected

我正在设置计划任务以注销断开连接的会话。我使用打开 PowerShell.exe 的操作设置任务,参数如下所示

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

该参数在 PowerShell 中独立运行,但当我尝试创建此任务时它失败并显示错误:

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

我认为我需要对表达式进行求值才能正确填充字符串,并尝试转义引号和括号以使其正常工作。任何帮助将不胜感激。

您的问题可能出在引号上。请注意,您必须正确引用和转义命令行参数。为简单起见,您可以在命令中使用单引号,或者在不需要时将它们一起跳过。此外,Invoke-Command 是多余的。

试试这个:

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