Esempio di StopProcessSample01StopProcessSample01 Sample

In questo esempio viene illustrato come scrivere un cmdlet che richiede feedback da parte dell'utente prima di tentare di arrestare un processo e come implementare un PassThru parametro che indica che l'utente desidera che il cmdlet restituisca un oggetto.This sample shows how to write a cmdlet that requests feedback from the user before it attempts to stop a process, and how to implement a PassThru parameter indicating that the user wants the cmdlet to return an object. Questo cmdlet è simile al Stop-Process cmdlet fornito da Windows PowerShell 2,0.This cmdlet is similar to the Stop-Process cmdlet provided by Windows PowerShell 2.0.

Come compilare l'esempio usando Visual Studio.How to build the sample by using Visual Studio.

  1. Con Windows PowerShell 2,0 SDK installato, passare alla cartella StopProcessSample01.With the Windows PowerShell 2.0 SDK installed, navigate to the StopProcessSample01 folder. Il percorso predefinito è C:\Programmi (x86) \Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\StopProcessSample01.The default location is C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0\Samples\sysmgmt\WindowsPowerShell\csharp\StopProcessSample01.

  2. Fare doppio clic sull'icona del file di soluzione (con estensione sln).Double-click the icon for the solution (.sln) file. Verrà aperto il progetto di esempio in Microsoft Visual Studio.This opens the sample project in Microsoft Visual Studio.

  3. Scegliere Compila soluzione dal menu Compila.In the Build menu, select Build Solution.

    La libreria per l'esempio verrà compilata nelle cartelle \bin o \bin\Debug predefinite.The library for the sample will be built in the default \bin or \bin\debug folders.

Per eseguire l'esempioHow to run the sample

  1. Creare la cartella dei moduli seguente:Create the following module folder:

    [user]/documents/windowspowershell/modules/StopProcessSample01

  2. Copiare l'assembly di esempio nella cartella del modulo.Copy the sample assembly to the module folder.

  3. Avviare Windows PowerShell.Start Windows PowerShell.

  4. Eseguire il comando seguente per caricare l'assembly in Windows PowerShell:Run the following command to load the assembly into Windows PowerShell:

    import-module stopprossessample01

  5. Eseguire il comando seguente per eseguire il cmdlet:Run the following command to run the cmdlet:

    stop-proc

RequisitiRequirements

Questo esempio richiede Windows PowerShell 2,0.This sample requires Windows PowerShell 2.0.

DimostraDemonstrates

In questo esempio vengono illustrate le operazioni seguenti.This sample demonstrates the following.

  • Dichiarazione di una classe di cmdlet mediante l'attributo cmdlet.Declaring a cmdlet class by using the Cmdlet attribute.

  • Dichiarazione di parametri di cmdlet mediante l'attributo Parameter.Declaring a cmdlet parameters by using the Parameter attribute.

  • Chiamata del metodo ShouldProcess per richiedere la conferma.Calling the ShouldProcess method to request confirmation.

  • Implementazione di un PassThru parametro che indica se l'utente desidera che il cmdlet restituisca un oggetto.Implementing a PassThru parameter that indicates if the user wants the cmdlet to return an object. Per impostazione predefinita, questo cmdlet non restituisce un oggetto alla pipeline.By default, this cmdlet does not return an object to the pipeline.

EsempioExample

In questo esempio viene illustrato come implementare un PassThru parametro che indica che l'utente desidera che il cmdlet restituisca un oggetto e come richiedere il feedback dell'utente tramite chiamate ShouldProcess ai ShouldContinue metodi e.This sample shows how to implement a PassThru parameter that indicates that the user wants the cmdlet to return an object, and how to request user feedback by calls to the ShouldProcess and ShouldContinue methods.

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 nonterminating 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 nonterminating 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
}

Vedere ancheSee Also

Scrittura di un cmdlet di Windows PowerShellWriting a Windows PowerShell Cmdlet