LoginSignup
0
1

More than 1 year has passed since last update.

C#.NETでWindowsのタスクスケジューラー情報を取得したい

Posted at

やり方

プロジェクト作成

image.png

image.png

.NET Frameworkは4.8。
image.png

プロジェクト名は『TaskSchedulerExceptionCheck』にしてみた。

参照

TaskScheduler 1.1 Type Library にチェック。
image.png

サンプルコード

using System;
using TaskScheduler;

namespace TaskSchedulerExceptionCheck
{
    internal class Program
    {

        static void Main(string[] args)
        {

            ITaskService task_service_ = null;
            ITaskFolder root_folder_ = null;
            IRegisteredTaskCollection task_collection_ = null;

            try
            {
                task_service_ = new TaskScheduler.TaskScheduler();
                task_service_.Connect();

                //タスクスケジューラーはフォルダー階層構造を持っている。
                //今回はルートフォルダーのタスク一覧を対象にする。
                root_folder_ = task_service_.GetFolder("");

                task_collection_ = root_folder_.GetTasks(0);

                foreach (IRegisteredTask task_ in task_collection_)
                {
                    try
                    {
                        //サンプルコードなのでとりあえず「こんな情報がとれるんだね。ふーん」ができればよい。
                        Console.WriteLine(task_.Name);
                        Console.WriteLine(task_.LastRunTime);
                        Console.WriteLine(task_.LastTaskResult);
                    }
                    finally
                    {
                        if (task_ != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(task_);
                    }
                }

            }
            //サンプルコードなのでcatchはやらん。
            finally
            {
                if (task_service_ != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(task_service_);
                if (root_folder_ != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(root_folder_);
                if (task_collection_ != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(task_collection_);
            }

            //結果確認用にコンソール画面閉じずに残す。
            Console.ReadLine();

        }
    }
}

exe実行結果

うん。情報取れますね。
image.png

蛇足

サンプルを発展させていけば…
『何かの例外でずーっと実行中のままになっちゃってるタスクを検知してメール通知』
とかできるかなあって思ってる。

参考サイトさん

バージョン

Windows 10 Pro 21H2 OSビルド 19045.2311
Microsoft Visual Studio Community 2022 (64 ビット) - Current Version 17.3.6
Microsoft .NET Framework Version 4.8.04084

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1