Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Kode berikut menunjukkan implementasi Get-Process
cmdlet yang melaporkan kesalahan yang tidak mengakhiri. Implementasi ini menggunakan metode System.Management.Automation.Cmdlet.WriteError untuk melaporkan kesalahan yang tidak menghentikan proses.
Nota
Anda dapat mengunduh file sumber C# (getprov04.cs) untuk cmdlet Get-Proc ini menggunakan Kit Pengembangan Perangkat Lunak Microsoft Windows untuk Komponen Runtime Windows Vista dan .NET Framework 3.0. Untuk petunjuk pengunduhan, lihat Cara Menginstal Windows PowerShell dan Mengunduh Windows PowerShell SDK. File sumber yang diunduh tersedia di direktori<>.
Sampel Kode
namespace Microsoft.Samples.PowerShell.Commands
{
using System;
using System.Diagnostics;
using System.Management.Automation; // Windows PowerShell namespace.
#region GetProcCommand
/// <summary>
/// This class implements the get-proc cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Proc")]
public class GetProcCommand : Cmdlet
{
#region Parameters
/// <summary>
/// The names of the processes to act on.
/// </summary>
private string[] processNames;
/// <summary>
/// Gets or sets the list of process names on
/// which the Get-Proc cmdlet will work.
/// </summary>
[Parameter(
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string[] Name
{
get { return this.processNames; }
set { this.processNames = value; }
}
#endregion Parameters
#region Cmdlet Overrides
/// <summary>
/// The ProcessRecord method calls the Process.GetProcesses
/// method to retrieve the processes specified by the Name
/// parameter. Then, the WriteObject method writes the
/// associated processes to the pipeline.
/// </summary>
protected override void ProcessRecord()
{
// If no process names are passed to cmdlet, get all
// processes.
if (this.processNames == null)
{
WriteObject(Process.GetProcesses(), true);
}
else
{
// If process names are passed to the cmdlet, get and write
// the associated processes.
// If a nonterminating error occurs while retrieving processes,
// call the WriteError method to send an error record to the
// error stream.
foreach (string name in this.processNames)
{
Process[] processes;
try
{
processes = Process.GetProcessesByName(name);
}
catch (InvalidOperationException ex)
{
WriteError(new ErrorRecord(
ex,
"UnableToAccessProcessByName",
ErrorCategory.InvalidOperation,
name));
continue;
}
WriteObject(processes, true);
} // foreach (string name...
} // else
} // ProcessRecord
#endregion Overrides
} // End GetProcCommand class.
#endregion GetProcCommand
}