[玩转系统] StopProcessSample04 (C#) 示例代码
作者:精品下载站 日期:2024-12-14 02:28:12 浏览:15 分类:玩电脑
StopProcessSample04 (C#) 示例代码
以下是 StopProc04 示例 cmdlet 的完整 C# 示例代码。这是向 Cmdlet 添加参数集中描述的 Stop-Process
cmdlet 的代码。 Stop-Process
cmdlet 旨在停止使用 Get-Proc cmdlet 检索的进程(在创建您的第一个 Cmdlet 中进行了描述)。
笔记
您可以使用适用于 Windows Vista 和 .NET Framework 3.0 运行时组件的 Microsoft Windows 软件开发工具包下载此 Stop-Proc cmdlet 的 C# (stopprocesssample04.cs) 源文件。有关下载说明,请参阅如何安装 Windows PowerShell 和下载 Windows PowerShell SDK。下载的源文件位于 目录中。
using System;
using System.Diagnostics;
using System.Collections;
using Win32Exception = System.ComponentModel.Win32Exception;
using System.Management.Automation; //Windows PowerShell namespace
using System.Globalization;
// This sample shows how to declare parameter sets, the input object, and
// how to specify the default parameter set to use.
//
// To test this cmdlet, create a module folder that has the same name as
// this assembly (StopProcesssample04), save the assembly in the module folder, and then run the
// following command:
// import-module stopprocesssample04
namespace Microsoft.Samples.PowerShell.Commands
{
#region StopProcCommand
/// <summary>
/// This class implements the stop-proc cmdlet.
/// </summary>
[Cmdlet(VerbsLifecycle.Stop, "Proc",
DefaultParameterSetName = "ProcessId",
SupportsShouldProcess = true)]
public class StopProcCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// This parameter provides the list of process names on
/// which the Stop-Proc cmdlet will work.
/// </summary>
[Parameter(
Position = 0,
ParameterSetName = "ProcessName",
Mandatory = true,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of one or more processes to stop. Wildcards are permitted."
)]
[Alias("ProcessName")]
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(
HelpMessage = "If set the process(es) will be passed to the pipeline after stopped."
)]
public SwitchParameter PassThru
{
get { return passThru; }
set { passThru = value; }
}
private bool passThru;
/// This parameter provides the list of process identifiers on
/// which the Stop-Proc cmdlet will work.
[Parameter(
ParameterSetName = "ProcessId",
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = true
)]
[Alias("ProcessId")]
public int[] Id
{
get { return processIds; }
set { processIds = value; }
}
private int[] processIds;
/// <summary>
/// This parameter accepts an array of Process objects from the
/// the pipeline. This object contains the processes to stop.
/// </summary>
/// <value>Process objects</value>
[Parameter(
ParameterSetName = "InputObject",
Mandatory = true,
ValueFromPipeline = true)]
public Process[] InputObject
{
get { return inputObject; }
set { inputObject = value; }
}
private Process[] inputObject;
#endregion Parameters
#region CmdletOverrides
/// <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()
{
switch (ParameterSetName)
{
case "ProcessName":
ProcessByName();
break;
case "ProcessId":
ProcessById();
break;
case "InputObject":
foreach (Process process in inputObject)
{
SafeStopProcess(process);
}
break;
default:
throw new ArgumentException("Bad ParameterSet Name");
} // switch (ParameterSetName...
} // ProcessRecord
#endregion Cmdlet Overrides
#region Helper Methods
/// <summary>
/// Returns all processes with matching names.
/// </summary>
/// <param name="processName">
/// The name of the processes to return.
/// </param>
/// <param name="allProcesses">An array of all
/// computer processes.</param>
/// <returns>An array of matching processes.</returns>
internal ArrayList SafeGetProcessesByName(string processName,
ref ArrayList allProcesses)
{
// Create and array to store the matching processes.
ArrayList matchingProcesses = new ArrayList();
// Create the wildcard for pattern matching.
WildcardOptions options = WildcardOptions.IgnoreCase |
WildcardOptions.Compiled;
WildcardPattern wildcard = new WildcardPattern(processName, options);
// Walk all of the machine processes.
foreach(Process process in allProcesses)
{
string processNameToMatch = null;
try
{
processNameToMatch = process.ProcessName;
}
catch (Win32Exception e)
{
// Remove the process from the list so that it is not
// checked again.
allProcesses.Remove(process);
string message =
String.Format(CultureInfo.CurrentCulture, "The process \"{0}\" could not be found",
processName);
WriteVerbose(message);
WriteError(new ErrorRecord(e, "ProcessNotFound",
ErrorCategory.ObjectNotFound, processName));
continue;
}
if (!wildcard.IsMatch(processNameToMatch))
{
continue;
}
matchingProcesses.Add(process);
} // foreach(Process...
return matchingProcesses;
} // SafeGetProcessesByName
/// <summary>
/// Safely stops a named process. Used as standalone function
/// to declutter the ProcessRecord method.
/// </summary>
/// <param name="process">The process to stop.</param>
private void SafeStopProcess(Process process)
{
string processName = null;
try
{
processName = process.ProcessName;
}
catch (Win32Exception e)
{
WriteError(new ErrorRecord(e, "ProcessNotFound",
ErrorCategory.OpenError, processName));
return;
}
// Confirm the operation first.
// This is always false if the WhatIf parameter is specified.
if (!ShouldProcess(string.Format(CultureInfo.CurrentCulture,
"{0} ({1})", processName, process.Id)))
{
return;
}
// Make sure that the user really wants to stop a critical
// process that can possibly stop the computer.
bool criticalProcess = criticalProcessNames.Contains(processName.ToLower(CultureInfo.CurrentCulture));
string message = null;
if (criticalProcess && !force)
{
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 recieved as inputs from
// the pipeline. So to retain YesToAll and NoToAll input that
// the user may enter across mutilple calls to this function,
// they are stored as private members of the cmdlet.
if (!ShouldContinue(message, "Warning!",
ref yesToAll, ref noToAll))
{
return;
}
} // if (criticalProcess...
// Display a warning message if stopping a critical
// process.
if (criticalProcess)
{
message =
String.Format(CultureInfo.CurrentCulture,
"Stopping the critical process \"{0}\".",
processName);
WriteWarning(message);
} // if (criticalProcess...
try
{
// Stop the process.
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)
);
return;
} // if ((e is...
else throw;
} // catch
// Write a user-level verbose message to the pipeline. These are
// intended to give the user detailed information on the
// operations performed by the cmdlet. These messages will
// appear with the -Verbose option.
message = String.Format(CultureInfo.CurrentCulture,
"Stopped process \"{0}\", pid {1}.",
processName, process.Id);
WriteVerbose(message);
// If the PassThru prameter is specified, return the terminated
// process to the pipeline.
if (passThru)
{
// Write a debug message to the host that can be used
// when troubleshooting a problem. All debug messages
// will appear with the -Debug option
message =
String.Format(CultureInfo.CurrentCulture,
"Writing process \"{0}\" to pipeline",
processName);
WriteDebug(message);
WriteObject(process);
} // if (passThru..
} // SafeStopProcess
/// <summary>
/// Stop processes based on their names (using the
/// ParameterSetName as ProcessName)
/// </summary>
private void ProcessByName()
{
ArrayList allProcesses = null;
// Get a list of all processes.
try
{
allProcesses = new ArrayList(Process.GetProcesses());
}
catch (InvalidOperationException ioe)
{
base.ThrowTerminatingError(new ErrorRecord(
ioe, "UnableToAccessProcessList",
ErrorCategory.InvalidOperation, null));
}
// If a process name is passed to the cmdlet, get
// the associated processes.
// Write a nonterminating error for failure to
// retrieve a process.
foreach (string name in processNames)
{
// The allProcesses array list is passed as a reference because
// any process whose name cannot be obtained will be removed
// from the list so that its not compared the next time.
ArrayList processes =
SafeGetProcessesByName(name, ref allProcesses);
// If no processes were found write a non-
// terminating error.
if (processes.Count == 0)
{
WriteError(new ErrorRecord(
new Exception("Process not found."),
"ProcessNotFound",
ErrorCategory.ObjectNotFound,
name));
} // if (processes...
// Otherwise terminate all processes in the list.
else
{
foreach (Process process in processes)
{
SafeStopProcess(process);
} // foreach (Process...
} // else
} // foreach (string...
} // ProcessByName
/// <summary>
/// Stop processes based on their identifiers (using the
/// ParameterSetName as ProcessIds)
/// </summary>
internal void ProcessById()
{
foreach (int processId in processIds)
{
Process process = null;
try
{
process = Process.GetProcessById(processId);
// Write a debug message to the host that can be used
// when troubleshooting a problem. All debug messages
// will appear with the -Debug option
string message =
String.Format(CultureInfo.CurrentCulture,
"Acquired process for pid : {0}",
process.Id);
WriteDebug(message);
}
catch (ArgumentException ae)
{
string
message = String.Format(CultureInfo.CurrentCulture,
"The process id {0} could not be found",
processId);
WriteVerbose(message);
WriteError(new ErrorRecord(ae, "ProcessIdNotFound",
ErrorCategory.ObjectNotFound, processId));
continue;
}
SafeStopProcess(process);
} // foreach (int...
} // ProcessById
#endregion Helper Methods
#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", "calc" }
);
#endregion Private Data
} // StopProcCommand
#endregion StopProcCommand
}
参见
Windows PowerShell 程序员指南
Windows PowerShell SDK
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag