Пример командлета GetProcessSample01
В этом примере показано, как реализовать командлет, который извлекает процессы на локальном компьютере. Этот командлет представляет собой упрощенную версию командлета Get-Process
, предоставляемого Windows PowerShell 2.0.
Создание примера с помощью Visual Studio
Установив пакет SDK для Windows PowerShell 2.0, перейдите в папку GetProcessSample01. По умолчанию он расположен в папке
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\GetProcessSample01
.Дважды щелкните значок для файла решения (.sln). Откроется пример проекта в Microsoft Visual Studio.
В меню Сборка выберите Сборка решения, чтобы создать библиотеку для примера в папках
\bin
по умолчанию или\bin\debug
.
Запуск примера
Откройте окно командной строки.
Перейдите в каталог, содержащий пример файла .dll.
Выполните
installutil "GetProcessSample01.dll"
.Запустите Windows PowerShell.
Выполните следующую команду, чтобы добавить оснастку в оболочку.
Add-PSSnapin GetProcPSSnapIn01
Введите следующую команду, чтобы запустить командлет.
Get-Proc
Get-Proc
Это пример выходных данных, который приводит к следующим шагам.
Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 26932870-d3b... NotStarted False Write-Host "A f...
Set-Content $Env:TEMP\test.txt "This is a test file"
A file was created in the TEMP directory
Требования
Для этого примера требуется Windows PowerShell 1.0 или более поздней версии.
Демонстрирует
В этом примере показано следующее.
Создание базового примера командлета.
Определение класса командлета с помощью атрибута Командлета.
Создание оснастки, которая работает с Windows PowerShell 1.0 и Windows PowerShell 2.0. В последующих примерах используются модули вместо оснастки, поэтому для них требуется Windows PowerShell 2.0.
Пример
В этом примере показано, как создать простой командлет и его оснастку.
using System;
using System.Diagnostics;
using System.Management.Automation; //Windows PowerShell namespace
using System.ComponentModel;
namespace Microsoft.Samples.PowerShell.Commands
{
#region GetProcCommand
/// <summary>
/// This class implements the Get-Proc cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Proc")]
public class GetProcCommand : Cmdlet
{
#region Cmdlet Overrides
/// <summary>
/// The ProcessRecord method calls the Process.GetProcesses
/// method to retrieve the processes of the local computer.
/// Then, the WriteObject method writes the associated processes
/// to the pipeline.
/// </summary>
protected override void ProcessRecord()
{
// Retrieve the current processes.
Process[] processes = Process.GetProcesses();
// Write the processes to the pipeline to make them available
// to the next cmdlet. The second argument (true) tells Windows
// PowerShell to enumerate the array and to send one process
// object at a time to the pipeline.
WriteObject(processes, true);
}
#endregion Overrides
} //GetProcCommand
#endregion GetProcCommand
#region PowerShell snap-in
/// <summary>
/// Create this sample as a PowerShell snap-in
/// </summary>
[RunInstaller(true)]
public class GetProcPSSnapIn01 : PSSnapIn
{
/// <summary>
/// Create an instance of the GetProcPSSnapIn01
/// </summary>
public GetProcPSSnapIn01()
: base()
{
}
/// <summary>
/// Get a name for this PowerShell snap-in. This name will be used in registering
/// this PowerShell snap-in.
/// </summary>
public override string Name
{
get
{
return "GetProcPSSnapIn01";
}
}
/// <summary>
/// Vendor information for this PowerShell snap-in.
/// </summary>
public override string Vendor
{
get
{
return "Microsoft";
}
}
/// <summary>
/// Gets resource information for vendor. This is a string of format:
/// resourceBaseName,resourceName.
/// </summary>
public override string VendorResource
{
get
{
return "GetProcPSSnapIn01,Microsoft";
}
}
/// <summary>
/// Description of this PowerShell snap-in.
/// </summary>
public override string Description
{
get
{
return "This is a PowerShell snap-in that includes the Get-Proc cmdlet.";
}
}
}
#endregion PowerShell snap-in
}
См. также
PowerShell