如何支持作业
此示例演示如何在编写 cmdlet 时支持作业。 如果希望用户将 cmdlet 作为后台作业运行,则必须包括以下过程中所述的代码。 有关后台作业的详细信息,请参阅 后台作业。
支持作业
定义
AsJob
开关参数,使用户可以决定是否将 cmdlet 作为作业运行。下面的示例演示了 AsJob 参数声明。
[Parameter()] public SwitchParameter AsJob { get { return asjob; } set { asjob = value; } } private bool asjob;
创建一个派生自 system.object 类的对象。 此对象可以是自定义作业对象,也可以是 Windows PowerShell 提供的作业对象之一,如Pseventjob对象。
下面的示例演示一个自定义作业对象。
private SampleJob job = new SampleJob("Get-ProcAsJob");
在记录处理方法中,添加
if
语句以检测 cmdlet 是否应作为作业运行。 下面的代码使用 ProcessRecord 方法来实现。protected override void ProcessRecord() { if (asjob) { // Add the job definition to the job repository, // return the job object, and then create the thread // used to run the job. JobRepository.Add(job); WriteObject(job); ThreadPool.QueueUserWorkItem(WorkItem); } else { job.ProcessJob(); foreach (PSObject p in job.Output) { WriteObject(p); } } }
对于自定义作业对象,请实现 job 类。
private class SampleJob : Job { internal SampleJob(string command) : base(command) { SetJobState(JobState.NotStarted); } public override string StatusMessage { get { throw new NotImplementedException(); } } public override bool HasMoreData { get { return hasMoreData; } } private bool hasMoreData = true; public override string Location { get { throw new NotImplementedException(); } } public override void StopJob() { throw new NotImplementedException(); } internal void ProcessJob() { SetJobState(JobState.Running); DoProcessLogic(); SetJobState(JobState.Completed); } // Retrieve the processes of the local computer. void DoProcessLogic() { Process[] p = Process.GetProcesses(); foreach (Process pl in p) { Output.Add(PSObject.AsPSObject(pl)); } Output.Complete(); } // End DoProcessLogic. } // End SampleJob class.
如果该 cmdlet 执行工作,请调用 WriteObject 方法,以将进程对象返回到管道。 如果以作业的形式执行工作,请将子作业添加到作业。
void DoProcessLogic(bool asJob) { Process[] p = Process.GetProcesses(); foreach (Process pl in p) { if (!asjob) { WriteObject(pl); } else { job.ChildJobs[0].Output.Add(PSObject.AsPSObject(pl)); } } } // End DoProcessLogic.
示例
下面的示例代码演示了一个 cmdlet 的代码 Get-Proc
,该代码可在内部或通过使用后台作业检索进程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation; // Windows PowerShell namespace.
using System.Threading; // Thread pool namespace for posting work.
using System.Diagnostics; // Diagnostics namespace for retrieving
// process objects.
// This sample shows a cmdlet whose work can be done by the cmdlet or by using
// a background job. Background jobs are executed in their own thread,
// independent of the pipeline thread in which the cmdlet is executed.
//
// To load this cmdlet, create a module folder and copy the GetProcessSample06.dll
// assembly into the module folder. Make sure that the path to the module folder
// is added to the $PSModulePath environment variable.
// Module folder path:
// user/documents/WindowsPowerShell/modules/GetProcessSample06
//
// To import the module, run the following command: Import-Module GetProcessSample06.
// To test the cmdlet, run the following command: Get-Proc -name <process name>
//
//
namespace Microsoft.Samples.PowerShell.Commands
{
/// <summary>
/// This cmdlet retrieves process internally or returns
/// a job that retrieves the processes.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Proc")]
public sealed class GetProcCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Specify the Name parameter. This parameter accepts
/// process names from the command line.
/// </summary>
[Parameter(
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string[] Name
{
get { return processNames; }
set { processNames = value; }
}
private string[] processNames;
/// <summary>
/// Specify the AsJob parameter. This parameter indicates
/// whether the cmdlet should retrieve the processes internally
/// or return a Job object that retrieves the processes.
/// </summary>
[Parameter()]
public SwitchParameter AsJob
{
get { return asjob; }
set { asjob = value; }
}
private bool asjob;
#endregion Parameters
#region Cmdlet Overrides
// Create a custom job object.
private SampleJob job = new SampleJob("Get-ProcAsJob");
/// <summary>
/// Determines if the processes should be retrieved
/// internally or if a Job object should be returned.
/// </summary>
protected override void ProcessRecord()
{
if (asjob)
{
// Add the job definition to the job repository,
// return the job object, and then create the thread
// used to run the job.
JobRepository.Add(job);
WriteObject(job);
ThreadPool.QueueUserWorkItem(WorkItem);
}
else
{
job.ProcessJob();
foreach (PSObject p in job.Output)
{
WriteObject(p);
}
}
}
#endregion Overrides
// Implement a custom job that derives
// from the System.Management.Automation.Job class.
private class SampleJob : Job
{
internal SampleJob(string command)
: base(command)
{
SetJobState(JobState.NotStarted);
}
public override string StatusMessage
{
get { throw new NotImplementedException(); }
}
public override bool HasMoreData
{
get
{
return hasMoreData;
}
}
private bool hasMoreData = true;
public override string Location
{
get { throw new NotImplementedException(); }
}
public override void StopJob()
{
throw new NotImplementedException();
}
internal void ProcessJob()
{
SetJobState(JobState.Running);
DoProcessLogic();
SetJobState(JobState.Completed);
}
// Retrieve the processes of the local computer.
void DoProcessLogic()
{
Process[] p = Process.GetProcesses();
foreach (Process pl in p)
{
Output.Add(PSObject.AsPSObject(pl));
}
Output.Complete();
} // End DoProcessLogic.
} // End SampleJob class.
void WorkItem(object dummy)
{
job.ProcessJob();
}
// Display the results of the work. If not a job,
// process objects are returned. If a job, the
// output is added to the job as a child job.
void DoProcessLogic(bool asJob)
{
Process[] p = Process.GetProcesses();
foreach (Process pl in p)
{
if (!asjob)
{
WriteObject(pl);
}
else
{
job.ChildJobs[0].Output.Add(PSObject.AsPSObject(pl));
}
}
} // End DoProcessLogic.
} //End GetProcCommand
}
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈