Get-ScheduledTask 命令在 Windows Server 2008 R2 中不起作用

Get-ScheduledTask command does not work in Windows Server 2008 R2

我正在尝试查找名称中包含特定模式的计划任务,在我的情况下,计划任务的名称中应包含此模式 "ServiceNow"。为此,我使用 Get-ScheduledTask 命令,但此命令在 Windows Server 2008 R2 中失败。

$taskPattern = "ServiceNow"
$taskDetails = Get-ScheduledTask | Where-Object {$_.TaskName -match $taskPattern  }
$taskName = $taskDetails.TaskName

此脚本因错误而失败:

"Get-ScheduledTask : The term 'Get-ScheduledTask' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

然后我尝试了这种方法,它给了我“(任务名称日期和时间状态)”,但我不知道如何只从它的输出中提取任务名称。

$taskPattern = "ServiceNow" 
$taskExists = schtasks /query | select-string -patt $taskPattern 
$taskExists

任何人都可以告诉我如何通过仅提取实际任务名称使其在 Windows Server 2008 R2 中工作吗? 提前致谢

您无法在 windows 2008 R2 中获得 Get-ScheduledTask,因为它是为 Windows 2012 引入的,并且没有人向后移植它。有关更多信息,请参阅 github 上的 link。

最能描述情况的评论是:

Hi @dronkoff - This module is supported on PS 4.0. However, the problem isn't in the version of PowerShell. The issue is that the ScheduledTasks module, which this resource depends on, is not built into Windows Server 2008R2. It was first included in Windows Server 2012.

This is the case with many of the PowerShell modules: They are missing from older versions of Windows (Networking for example). In the odd occasion there is an easy work around. However in this case converting the resource over to use schtasks.exe is not possible without a complete rewrite and would probably result in something really unstable and buggy (not to mention the problems that would arise with different localized versions of schtasks). I really can't see this happening unfortunately (unless someone else from the community has some ideas on how to do this).

But you are correct, this should be mentioned that Windows Server 2008R2 is not currently supported.

解决方法

绕过它的方法是使用 schtask 和正确的开关。

如果你把它放在 Microsoft 文件夹中,就像我在示例中那样,你只需要 运行:

schtasks /tn \Microsoft\ServiceNow /query /fo LIST

输出:

Folder: \Microsoft
HostName:      XXXXXACL06
TaskName:      \Microsoft\ServiceNow
Next Run Time: 7/4/2018 8:16:22 AM
Status:        Ready
Logon Mode:    Interactive only

如果您需要更多详细信息,可以使用 /v(详细)开关:

schtasks /tn \Microsoft\ServiceNow /query /v > service_now_details.txt

编辑 - 寻找模式

如果您只有模式要搜索,则必须使用一些额外的工具来搜索字符串。 windows 在 powershell 中原生支持 findstr(或 Select-String(简称 sls)):

要查找您可以使用的任务名称:

schtasks /query /fo LIST | findstr "ServiceNow"

或者即使是狂野包机

schtasks /query /fo LIST | findstr "ServiceNo*"

powershell 方式:

schtasks /query /fo LIST | sls 'ServiceNo*'

所有情况下的输出都是这样的(因为我的任务完全命名为 ServiceNow):

TaskName: \Microsoft\ServiceNow

Edit2 区分大小写

如果您要搜索不区分大小写的字符串,则: 对于 findstr,您必须添加 /I 以使其不敏感。 powershell的select-string(sls)天生不敏感

GitHub、Get-ScheduledTasks 上有一个很棒的脚本(注意服务名称末尾的 S)。这适用于旧版本的 Windows 回到 Windows Server 2003 / Windows XP。

感谢出色的 Warren F(又名 Rambling Cookie Monster)创建和分享此内容。