如何支援作業
此範例示範如何在撰寫 Cmdlet 時支援工作。 如果您想要讓使用者以背景工作的方式執行 Cmdlet,則必須包含下列程式中所述的程式碼。 如需背景工作的詳細資訊,請參閱 背景工作。
支援作業
定義
AsJob
切換參數,讓使用者可以決定是否要以工作的形式執行 Cmdlet。下列範例顯示 AsJob 參數宣告。
[Parameter()] public SwitchParameter AsJob { get { return asjob; } set { asjob = value; } } private bool asjob;
建立一個衍生自system.string 類別的物件。 這個物件可以是自訂工作物件或 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
}