简体   繁体   中英

How to create collection of scheduler task path in powershell script

I have a powershell script where I have to enable or disable task. In the script following thing I'm doing

  1. read the $TaskPath = '\Microsoft\Windows\PowerShell\ScheduledJobs'
  2. Get-ScheduledTask via $TaskPath
  3. Get-ScheduledJob

Now in my project we have many different schedule task which is present in different path like few present at '\Microsoft\Windows\PowerShell\ScheduledJobs' and some task present at root path like '\printtask'.

Now when I pass the taskname to execute in the script and if that task is not present in the $TaskPath = '\Microsoft\Windows\PowerShell\ScheduledJobs' then it will not execute. To solve this issue I have to add another if condition for setting root path.

Lets say in the future if we have new task with some different path then I have to again add new if condition. To avoid that situation I am looking a way to have collection/list of task paths to check, Then we go through that collection/list and find the scheduled job and execute.

If in the future we need to add new task with other path, we can just add that task path to that collection/list and avoid having additional if statement.

Anyone has any suggestion how I can archive this..?

在此处输入图像描述

You can store all the TaskPaths in your initial logic by building an array of objects and add all of your Task Paths in there, somewhat like this:

$TaskPathList = @()
$TaskPathList += New-Object -TypeName PSObject -Property @{TaskPath = $TaskPath1;}
$TaskPathList += New-Object -TypeName PSObject -Property @{TaskPath = $TaskPath2;}

Later on, you can iterate through this collection of TaskPaths to read them do the decision making accordingly:

$TaskPathList | ForEach-Object {
    if(<Place your condition to check against $_.TaskPath >)
    {
        #Do your stuff
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM