[玩转系统] StopProcessSample04 (VB.NET) 示例代码
作者:精品下载站 日期:2024-12-14 02:28:09 浏览:12 分类:玩电脑
StopProcessSample04 (VB.NET) 示例代码
以下是 StopProc04 示例 cmdlet 的完整 VB.NET 示例代码。这是向 Cmdlet 添加参数集中描述的 Stop-Process
cmdlet 的代码。 Stop-Process
cmdlet 旨在停止使用 Get-Proc cmdlet 检索的进程(在创建您的第一个 Cmdlet 中进行了描述)。
笔记
您可以使用适用于 Windows Vista 和 .NET Framework 3.0 运行时组件的 Microsoft Windows 软件开发工具包下载此 Stop-Proc cmdlet 的 VB.NET (stopprocesssample04.vb) 源文件。有关下载说明,请参阅如何安装 Windows PowerShell 和下载 Windows PowerShell SDK。
下载的源文件位于 目录中。
Imports System
Imports System.Diagnostics
Imports System.Collections
Imports Win32Exception = System.ComponentModel.Win32Exception
Imports System.Management.Automation 'Windows PowerShell namespace
Imports System.ComponentModel
Imports System.Globalization
Namespace Microsoft.Samples.PowerShell.Commands
' This sample introduces parameter sets, the input object and
' DefaultParameterSet.
#Region "StopProcCommand"
''' <summary>
''' Class that implements the stop-proc cmdlet.
''' </summary>
<Cmdlet(VerbsLifecycle.Stop, "Proc", DefaultParameterSetName:="ProcessId", _
SupportsShouldProcess:=True)> _
Public Class StopProcCommand
Inherits PSCmdlet
#Region "Parameters"
''' <summary>
''' The list of process names on which this 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 Property Name() As String()
Get
Return processNames
End Get
Set(ByVal value As String())
processNames = value
End Set
End Property
Private processNames() As String
''' <summary>
''' Overrides the ShouldContinue check to force stop operation.
''' This option should always be used with caution.
''' </summary>
<Parameter()> _
Public Property Force() As SwitchParameter
Get
Return myForce
End Get
Set(ByVal value As SwitchParameter)
myForce = value
End Set
End Property
Private myForce As Boolean
''' <summary>
''' Common parameter to determine if the process should pass the
''' object down the pipeline after the process has been stopped.
''' </summary>
<Parameter( _
HelpMessage:= _
"If set the process(es) will be passed to the pipeline " & _
"after stopping them.")> _
Public Property PassThru() As SwitchParameter
Get
Return myPassThru
End Get
Set(ByVal value As SwitchParameter)
myPassThru = value
End Set
End Property
Private myPassThru As Boolean
''' <summary>
''' The list of process IDs on which this cmdlet will work.
''' </summary>
<Parameter(ParameterSetName:="ProcessId", _
Mandatory:=True, _
ValueFromPipelineByPropertyName:=True, _
ValueFromPipeline:=True), [Alias]("ProcessId")> _
Public Property Id() As Integer()
Get
Return processIds
End Get
Set(ByVal value As Integer())
processIds = value
End Set
End Property
Private processIds() As Integer
''' <summary>
''' An array of Process objects from the stream to stop.
''' </summary>
''' <value>Process objects</value>
<Parameter(ParameterSetName:="InputObject", _
Mandatory:=True, ValueFromPipeline:=True)> _
Public Property InputObject() As Process()
Get
Return myInputObject
End Get
Set(ByVal value As Process())
myInputObject = value
End Set
End Property
Private myInputObject() As Process
#End Region
#Region "CmdletOverrides"
''' <summary>
''' For each of the requested processnames:
''' 1) check it's not a special process
''' 2) attempt to stop that process.
''' If no process requested, then nothing occurs.
''' </summary>
Protected Overrides Sub ProcessRecord()
Select Case ParameterSetName
Case "ProcessName"
ProcessByName()
Case "ProcessId"
ProcessById()
Case "InputObject"
Dim process As Process
For Each process In myInputObject
SafeStopProcess(process)
Next process
Case Else
Throw New ArgumentException("Bad ParameterSet Name")
End Select
End Sub 'ProcessRecord ' ProcessRecord
#End Region
#Region "Helper Methods"
''' <summary>
''' Returns all processes with matching names.
''' </summary>
''' <param name="processName">
''' The name of the process(es) to return
''' </param>
''' <param name="allProcesses">An array of all
''' machine processes.</param>
''' <returns>An array of matching processes.</returns>
Friend Function SafeGetProcessesByName(ByVal processName As String, _
ByRef allProcesses As ArrayList) As ArrayList
' Create and array to store the matching processes.
Dim matchingProcesses As New ArrayList()
' Create the wildcard for pattern matching.
Dim options As WildcardOptions = WildcardOptions.IgnoreCase Or _
WildcardOptions.Compiled
Dim wildcard As New WildcardPattern(processName, options)
' Walk all of the machine processes.
Dim process As Process
For Each process In allProcesses
Dim processNameToMatch As String = Nothing
Try
processNameToMatch = process.ProcessName
Catch e As Win32Exception
' Remove the process from the list so that it is not
' checked again.
allProcesses.Remove(process)
Dim message As String = _
String.Format(CultureInfo.CurrentCulture, _
"The process ""{0}"" could not be found", processName)
WriteVerbose(message)
WriteError(New ErrorRecord(e, _
"ProcessNotFound", ErrorCategory.ObjectNotFound, _
processName))
GoTo ContinueForEach1
End Try
If Not wildcard.IsMatch(processNameToMatch) Then
GoTo ContinueForEach1
End If
matchingProcesses.Add(process)
ContinueForEach1:
Next process
Return matchingProcesses
End Function 'SafeGetProcessesByName
''' <summary>
''' Safely stops a named process. Used as standalone function
''' to declutter ProcessRecord method.
''' </summary>
''' <param name="process">The process to stop.</param>
Private Sub SafeStopProcess(ByVal process As Process)
Dim processName As String = Nothing
Try
processName = process.ProcessName
Catch e As Win32Exception
WriteError(New ErrorRecord(e, "ProcessNotFound", _
ErrorCategory.OpenError, processName))
Return
End Try
' Confirm the operation first.
' This is always false if WhatIf is set.
If Not ShouldProcess(String.Format(CultureInfo.CurrentCulture, _
"{0} ({1})", processName, process.Id)) Then
Return
End If
' Make sure the user really wants to stop a critical
' process and possibly stop the machine.
Dim criticalProcess As Boolean = _
criticalProcessNames.Contains( _
processName.ToLower(CultureInfo.CurrentCulture))
Dim message As String = Nothing
If criticalProcess AndAlso Not myForce Then
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 ProcessRecord is called multiple
' when objects are received as inputs from a 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 Not ShouldContinue(message, "Warning!", yesToAll, noToAll) Then
Return
End If
End If
' Display a warning information if stopping a critical
' process
If criticalProcess Then
message = String.Format(CultureInfo.CurrentCulture, _
"Stopping the critical process ""{0}"".", processName)
WriteWarning(message)
End If
Try
' Stop the process.
process.Kill()
Catch e As Exception
If TypeOf e Is Win32Exception OrElse TypeOf e Is SystemException _
OrElse TypeOf e Is InvalidOperationException Then
' This process could not be stopped so write
' a non-terminating error.
WriteError(New ErrorRecord(e, _
"CouldNotStopProcess", ErrorCategory.CloseError, process))
Return
Else
Throw
End If
End Try
' Write a user-level 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 command line argument is
' specified, pass the terminated process on.
If myPassThru Then
' Write a debug message to the host which will be helpful
' in 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)
End If
End Sub 'SafeStopProcess
''' <summary>
''' Stop processes based on their names (using the
''' ParameterSetName as ProcessName)
''' </summary>
Private Sub ProcessByName()
Dim allProcesses As ArrayList = Nothing
' Get a list of all processes.
Try
allProcesses = New ArrayList(Process.GetProcesses())
Catch ioe As InvalidOperationException
MyBase.ThrowTerminatingError(New ErrorRecord(ioe, _
"UnableToAccessProcessList", _
ErrorCategory.InvalidOperation, Nothing))
End Try
' If a name parameter is passed to cmdlet, get
' the associated process(es).
' Write a non-terminating error for failure to
' retrieve a process
Dim name As String
For Each 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.
Dim processes As ArrayList = SafeGetProcessesByName(name, _
allProcesses)
' If no processes were found write a non-terminating error.
If processes.Count = 0 Then
WriteError(New ErrorRecord( _
New Exception("Process not found."), _
"ProcessNotFound", ErrorCategory.ObjectNotFound, name))
Else
' Otherwise terminate all processes in the list.
Dim process As Process
For Each process In processes
SafeStopProcess(process)
Next process
End If
Next name
End Sub 'ProcessByName
''' <summary>
''' Stop processes based on their ids (using the
''' ParameterSetName as ProcessIds)
''' </summary>
Friend Sub ProcessById()
Dim processId As Integer
For Each processId In processIds
Dim process As Process = Nothing
Try
process = System.Diagnostics.Process.GetProcessById(processId)
' Write a debug message to the host which will be helpful
' in troubleshooting a problem. All debug messages
' will appear with the -Debug option
Dim message As String = String.Format( _
CultureInfo.CurrentCulture, _
"Acquired process for pid : {0}", process.Id)
WriteDebug(message)
Catch ae As ArgumentException
Dim message As String = String.Format( _
CultureInfo.CurrentCulture, _
"The process id {0} could not be found", processId)
WriteVerbose(message)
WriteError(New ErrorRecord(ae, _
"ProcessIdNotFound", _
ErrorCategory.ObjectNotFound, processId))
GoTo ContinueForEach1
End Try
SafeStopProcess(process)
ContinueForEach1:
Next processId
End Sub 'ProcessById ' ProcessById
#End Region
#Region "Private Data"
Private yesToAll, noToAll As Boolean
''' <summary>
''' Partial list of critical processes that should not be
''' stopped. Lower case is used for case insensitive matching.
''' </summary>
Private criticalProcessNames As New ArrayList( _
New String() {"system", "winlogon", "spoolsv", "calc"})
#End Region
End Class 'StopProcCommand
#End Region
#Region "PowerShell snap-in" '
''' <summary>
''' Create this sample as a PowerShell snap-in
''' </summary>
<RunInstaller(True)> _
Public Class StopProcPSSnapIn04
Inherits PSSnapIn
''' <summary>
''' Create an instance of the StopProcPSSnapIn04
''' </summary>
Public Sub New()
End Sub 'New
''' <summary>
''' Get a name for this PowerShell snap-in. This name will
''' be used in registering this PowerShell snap-in.
''' </summary>
Public Overrides ReadOnly Property Name() As String
Get
Return "StopProcPSSnapIn04"
End Get
End Property
''' <summary>
''' Vendor information for this PowerShell snap-in.
''' </summary>
Public Overrides ReadOnly Property Vendor() As String
Get
Return "Microsoft"
End Get
End Property
''' <summary>
''' Gets resource information for vendor. This is a string of format:
''' resourceBaseName,resourceName.
''' </summary>
Public Overrides ReadOnly Property VendorResource() As String
Get
Return "StopProcPSSnapIn04,Microsoft"
End Get
End Property
''' <summary>
''' Description of this PowerShell snap-in.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return "This is a PowerShell snap-in that includes " & _
"the stop-proc cmdlet."
End Get
End Property
End Class 'StopProcPSSnapIn04
#End Region
End Namespace
参见
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