이 샘플에서는 프로세스를 중지하기 전에 사용자의 피드백을 요청하는 cmdlet을 작성하는 방법과 사용자가 cmdlet이 개체를 반환하기를 원한다는 것을 나타내는 PassThru
매개 변수를 구현하는 방법을 보여 줍니다. 이 cmdlet은 Windows PowerShell 2.0에서 제공하는 Stop-Process
cmdlet과 유사합니다.
Visual Studio를 사용하여 샘플을 빌드하는 방법
Windows PowerShell 2.0 SDK가 설치된 상태에서 StopProcessSample01 폴더로 이동합니다. 기본 위치는
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\StopProcessSample01
입니다.솔루션(.sln) 파일의 아이콘을 두 번 클릭합니다. 그러면 Microsoft Visual Studio에서 샘플 프로젝트가 열립니다.
빌드 메뉴에서 빌드 솔루션 선택하여 기본
\bin
또는\bin\debug
폴더에서 샘플에 대한 라이브러리를 빌드합니다.
샘플을 실행하는 방법
다음 모듈 폴더를 만듭니다.
[user]\Documents\WindowsPowerShell\Modules\StopProcessSample01
샘플 어셈블리를 모듈 폴더에 복사합니다.
Windows PowerShell을 시작합니다.
다음 명령을 실행하여 Windows PowerShell에 어셈블리를 로드합니다.
Import-Module stopprossessample01
다음 명령을 실행하여 cmdlet을 실행합니다.
Stop-Proc
요구 사항
이 샘플에는 Windows PowerShell 2.0이 필요합니다.
입증합니다
이 샘플에서는 다음을 보여 줍니다.
Cmdlet 특성을 사용하여 cmdlet 클래스를 선언합니다.
매개 변수 특성을 사용하여 cmdlet 매개 변수 선언
ShouldProcess 메서드를 호출하여 확인을 요청합니다.
사용자가 cmdlet에서 개체를 반환할 것인지를 나타내는
PassThru
매개 변수 구현 기본적으로 이 cmdlet은 파이프라인에 개체를 반환하지 않습니다.
예시
이 샘플에서는 사용자가 cmdlet이 개체를 반환하기를 원한다는 것을 나타내는 PassThru
매개 변수를 구현하는 방법과 ShouldProcess
및 ShouldContinue
메서드를 호출하여 사용자 피드백을 요청하는 방법을 보여 줍니다.
using System;
using System.Diagnostics;
using System.Collections;
using Win32Exception = System.ComponentModel.Win32Exception;
using System.Management.Automation; // Windows PowerShell namespace
using System.Globalization;
namespace Microsoft.Samples.PowerShell.Commands
{
#region StopProcCommand
/// <summary>
/// This class implements the Stop-Proc cmdlet.
/// </summary>
[Cmdlet(VerbsLifecycle.Stop, "Proc",
SupportsShouldProcess = true)]
public class StopProcCommand : Cmdlet
{
#region Parameters
/// <summary>
/// This parameter provides the list of process names on
/// which the Stop-Proc cmdlet will work.
/// </summary>
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true
)]
public string[] Name
{
get { return processNames; }
set { processNames = value; }
}
private string[] processNames;
/// <summary>
/// This parameter overrides the ShouldContinue call to force
/// the cmdlet to stop its operation. This parameter should always
/// be used with caution.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get { return force; }
set { force = value; }
}
private bool force;
/// <summary>
/// This parameter indicates that the cmdlet should return
/// an object to the pipeline after the processing has been
/// completed.
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return passThru; }
set { passThru = value; }
}
private bool passThru;
#endregion Parameters
#region Cmdlet Overrides
/// <summary>
/// The ProcessRecord method does the following for each of the
/// requested process names:
/// 1) Check that the process is not a critical process.
/// 2) Attempt to stop that process.
/// If no process is requested then nothing occurs.
/// </summary>
protected override void ProcessRecord()
{
foreach (string name in processNames)
{
// For every process name passed to the cmdlet, get the associated
// processes.
// Write a non-terminating error for failure to retrieve
// a process.
Process[] processes;
try
{
processes = Process.GetProcessesByName(name);
}
catch (InvalidOperationException ioe)
{
WriteError(new ErrorRecord(ioe,"UnableToAccessProcessByName",
ErrorCategory.InvalidOperation, name));
continue;
}
// Try to stop the processes that have been retrieved.
foreach (Process process in processes)
{
string processName;
try
{
processName = process.ProcessName;
}
catch (Win32Exception e)
{
WriteError(new ErrorRecord(e, "ProcessNameNotFound",
ErrorCategory.ReadError, process));
continue;
}
// Confirm the operation with the user first.
// This is always false if the WhatIf parameter is set.
if (!ShouldProcess(string.Format(CultureInfo.CurrentCulture,"{0} ({1})", processName,
process.Id)))
{
continue;
}
// Make sure that the user really wants to stop a critical
// process that could possibly stop the computer.
bool criticalProcess =
criticalProcessNames.Contains(processName.ToLower(CultureInfo.CurrentCulture));
if (criticalProcess &&!force)
{
string message = String.Format
(CultureInfo.CurrentCulture,
"The process \"{0}\" is a critical process and should not be stopped. Are you sure you wish to stop the process?",
processName);
// It is possible that the ProcessRecord method is called
// multiple times when objects are received as inputs from
// the pipeline. So to retain YesToAll and NoToAll input that
// the user may enter across multiple calls to this function,
// they are stored as private members of the cmdlet.
if (!ShouldContinue(message, "Warning!",
ref yesToAll, ref noToAll))
{
continue;
}
} // if (criticalProcess...
// Stop the named process.
try
{
process.Kill();
}
catch (Exception e)
{
if ((e is Win32Exception) || (e is SystemException) ||
(e is InvalidOperationException))
{
// This process could not be stopped so write
// a non-terminating error.
WriteError(new ErrorRecord(e, "CouldNotStopProcess",
ErrorCategory.CloseError, process));
continue;
} // if ((e is...
else throw;
} // catch
// If the PassThru parameter is
// specified, return the terminated process.
if (passThru)
{
WriteObject(process);
}
} // foreach (Process...
} // foreach (string...
} // ProcessRecord
#endregion Cmdlet Overrides
#region Private Data
private bool yesToAll, noToAll;
/// <summary>
/// Partial list of critical processes that should not be
/// stopped. Lower case is used for case insensitive matching.
/// </summary>
private ArrayList criticalProcessNames = new ArrayList(
new string[] { "system", "winlogon", "spoolsv" }
);
#endregion Private Data
} // StopProcCommand
#endregion StopProcCommand
}
또한 참조하십시오
PowerShell