当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 更多 PowerShell 工具制作乐趣

作者:精品下载站 日期:2024-12-14 07:43:50 浏览:14 分类:玩电脑

更多 PowerShell 工具制作乐趣


[玩转系统] 更多 PowerShell 工具制作乐趣

因此,常见的任务是查找与特定状态(例如正在运行或已停止)相匹配的服务。您很可能见过这样的表达方式:

get-service -computername server01 | where {$_.status -eq 'running'}

这不是最繁琐的命令输入,但即使是我也输错了并且必须更正。如果这是一项常见任务,为什么不创建一个易于使用的工具呢?

#requires -version 3.0

Function Get-MyService {
 <# 
 .Synopsis
 Get services by status.
 .Description
 This is a proxy version of Get-Service. The only real change is that you can specify services by their status. The default is to get all running services.
 .Notes
 Created:	9/11/2014 

 Learn more:
  PowerShell in Depth: An Administrator's Guide (http://www.manning.com/jones6/)
  PowerShell Deep Dives (http://manning.com/hicks/)
  Learn PowerShell 3 in a Month of Lunches (http://manning.com/jones3/)
  Learn PowerShell Toolmaking in a Month of Lunches (http://manning.com/jones4/)
  
    ****************************************************************
    * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
    * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
    * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
    * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
    ****************************************************************
 
 .Example
 PS C:\> Get-MyService b* -status stopped -comp chi-dc04

Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  BITS               Background Intelligent Transfer Ser...
 
 .Link
 Get-Service
 
 #>

[CmdletBinding(DefaultParameterSetName='Default', RemotingCapability='SupportedByCommand')]
 param(
     [Parameter(ParameterSetName='Default', Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
     [Alias('ServiceName')]
     [string[]]$Name, 
     [ValidateNotNullorEmpty()]
     [System.ServiceProcess.ServiceControllerStatus]$Status="Running",
     [Parameter(ValueFromPipelineByPropertyName=$true)]
     [Alias('Cn')]
     [ValidateNotNullOrEmpty()]
     [string[]]$ComputerName = $env:COMPUTERNAME, 
     [Alias('DS')]
     [switch]$DependentServices, 
     [Alias('SDO','ServicesDependedOn')]
     [switch]$RequiredServices, 
     [Parameter(ParameterSetName='DisplayName', Mandatory=$true)]
     [string[]]$DisplayName, 
     [ValidateNotNullOrEmpty()]
     [string[]]$Include, 
     [ValidateNotNullOrEmpty()]
     [string[]]$Exclude, 
     [Parameter(ParameterSetName='InputObject', ValueFromPipeline=$true)]
     [ValidateNotNullOrEmpty()]
     [System.ServiceProcess.ServiceController[]]$InputObject
  ) 
  
 begin {
 
     Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"  

     Write-Verbose "Getting services with a status of $status on $($Computername.toUpper())"
 
     try {
         $outBuffer = $null
         if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
         {
             $PSBoundParameters['OutBuffer'] = 1
         }

         #remove Status parameter from bound parameters since Get-Service won't recognize it
         $PSBoundParameters.Remove("Status") | Out-Null

         $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-Service', [System.Management.Automation.CommandTypes]::Cmdlet)
         #$scriptCmd = {& $wrappedCmd @PSBoundParameters }
         #my modified command 
         $scriptCmd = {& $wrappedCmd @PSBoundParameters | Where-Object {$_.status -eq $Status } }
         $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
         $steppablePipeline.Begin($PSCmdlet)
     } catch {
         throw
     }
 } #begin
 
 process  {
     try {
         $steppablePipeline.Process($_)
     } catch {
         throw
     }
 } #process
 
 end {
     try {
         $steppablePipeline.End()
     } catch {
         throw
     }
     Write-Verbose -Message "Ending $($MyInvocation.Mycommand)" 
 } #end
  
} #end function Get-MyService

set-alias -Name gsv2 -Value Get-MyService

是的,我可以编写自己的函数来调用 Get-Service,但随后我必须编写所有代码来容纳 Get-Service 的所有参数。使用代理命令,我所需要做的就是插入我自己的代码。

#my modified command 
$scriptCmd = {& $wrappedCmd @PSBoundParameters | Where-Object {$_.status -eq $Status } }

换句话说,我让 Get-Service 做它的事情,然后过滤结果。现在我可以轻松地做到这一点:

PS C:\Scripts> get-myservice w* -Status stopped -ComputerName chi-dc01

Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  wbengine           Block Level Backup Engine Service     
Stopped  WbioSrvc           Windows Biometric Service             
Stopped  WcsPlugInService   Windows Color System                  
Stopped  WdiServiceHost     Diagnostic Service Host               
Stopped  WdiSystemHost      Diagnostic System Host                
Stopped  Wecsvc             Windows Event Collector               
Stopped  WinHttpAutoProx... WinHTTP Web Proxy Auto-Discovery Se...
Stopped  wmiApSrv           WMI Performance Adapter               
Stopped  wudfsvc            Windows Driver Foundation - User-mo...

或者,因为我正在输入此内容,所以我可以使用自己的别名。

我想指出的一件事是,对于新的 Status 属性,您会注意到我没有将其转换为字符串。

[System.ServiceProcess.ServiceControllerStatus]$Status="Running"

我本可以将其设为字符串,但通过使用实际枚举,PowerShell 将自动完成可能的值。

[玩转系统] 更多 PowerShell 工具制作乐趣

我怎么知道该用什么?我使用了获取会员。

PS C:\Scripts> get-service bits | get-member status

   TypeName: System.ServiceProcess.ServiceController

Name   MemberType Definition                                                 
----   ---------- ----------                                                 
Status Property   System.ServiceProcess.ServiceControllerStatus Status {get;}

这实际上并不那么困难或耗时。我写这篇博文的时间比创建该函数的时间还多。

我希望这会激励您创建自己的 PowerShell 工具,并分享您的劳动成果。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯