gpt4 book ai didi

powershell - Powershell用arg启动/停止

转载 作者:行者123 更新时间:2023-12-03 01:04:15 42 4
gpt4 key购买 nike

我已经在test.ps1中编写了以下函数,在运行该脚本以启动/停止/ ..时我想做一个选择:

function getState($SeviceName) { 
$server = @('host_1', 'host_2')

# get status
$server | % {Write-Host "verify: $_"; Get-Service -ComputerName $_ -Name SeviceName
}
  • 我想提供$ServiceName作为参数(使用stdin),我该怎么做? =>诸如此类的东西选择1开始2停止...
  • 在Powershell中使用开关/保护套
    $doAction = {"Stop-Service", "Start-service"}
    $server | % {Write-Host "verify: $_"; Get-Service -ComputerName $_ -Name SeviceName | $doAction}

  • 如何使用开关选择开始或停止?

    最佳答案

    这是一个可以满足您要求的函数:

    function Get-State {
    [CmdletBinding()]
    [OutputType('System.ServiceProcess.ServiceController')]
    param(
    [Parameter(Position = 0, Mandatory)]
    [ValidateSet('Start', 'Stop', 'Get')]
    [string] $Action,

    [Parameter(Position = 1, ValueFromPipeline, Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string] $ServiceName
    )

    begin {
    $serverList = @('host_1', 'host_2')
    }

    process {
    foreach ($server in $serverList) {
    try {
    $svc = Get-Service -ComputerName $server -Name $ServiceName -ErrorAction Stop
    } catch {
    throw "Failed to find service $ServiceName on $server! $PSItem"
    }

    switch ($Action) {
    'Start' { $svc | Start-Service -PassThru }
    'Stop' { $svc | Stop-Service -Force -PassThru }
    default { $svc }
    }
    }
    }
    }

    它利用高级功能和属性来进行管道输入(用词 stdin表示)。我建议 reading this documentation.

    关于powershell - Powershell用arg启动/停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51500776/

    42 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com