【问题标题】:Execute Multiline Powershell Script remotely远程执行多行 Powershell 脚本
【发布时间】:2022-10-12 22:34:26
【问题描述】:

我有一个脚本可以检查本地 IIS 系统上的 AppPool 状态。如果我们想排除某些 AppPool,它会在脚本命令行中输入。 如果命令行中没有提供排除列表,那么它基本上会找到 IIS 的所有 appPool 状态

现在我们需要的是在远程 IIS 服务器上远程执行脚本,而不是通过 winRM 的本地 IIS 服务器。

webAdministration 模块将仅存在于远程 IIS 服务器上,而不存在于执行脚本的本地服务器上。

那么我们如何引入 Invoke-Command 来通过 Remote Server 远程执行这样的多行脚本呢?

#Pass semi colon separated argument to exclude from being monitored eg Default Web Site;WebBDC3 (no quotation)

if (!$args.count -eq 0){
    $EA=$args.get(0).split(';')
}

Import-Module WebAdministration


$returnStateOK = 0
# $returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3

$statuses = @{
    ok = @()
    critical = @()
}

$criticalTitles = "";
$countCritical = 0;
$countOK = 0;

if (-Not ($EA)){
    $ApplicationPoolsState = Get-WebAppPoolState | % {  return  @{($_.itemxpath -split ("'"))[1]="$($_.value)" } } | % getEnumerator | % {
        if ($_.value -ne "Started"){
            $statuses.critical += $_.key
        }
        else{
            $statuses.ok += $_.key
        }
    }
}
else{
    [System.Collections.ArrayList]$ApplicationPoolsState = @() 
    Get-WebAppPoolState | % { 
      $count = $ApplicationPoolsState.add(@{($_.itemxpath -split ("'"))[1]="$($_.value)"})
    }
    foreach($h in $EA){
        if ($($ApplicationPoolsState.keys).IndexOf($h) -ge 0){
            $ApplicationPoolsState.RemoveAt($($ApplicationPoolsState.keys).IndexOf($h))
        }
    }
    $ApplicationPoolsState | % getEnumerator | % {
        if ($_.value -ne "Started"){
            $statuses.critical += $_.key
        }
        else{
            $statuses.ok += $_.key
        }
    }
}

$countCritical = $statuses.critical.length
$countOK = $statuses.ok.length

【问题讨论】:

    标签: powershell invoke-command winrm


    【解决方案1】:

    您只需定义一个脚本块并将其传递给invoke-command cmdlet 的参数-ScriptBlock,例如:

    $scriptblock = {
        #put your code in here
    }
    
    Invoke-Command -ComputerName [computername] -ScriptBlock $scriptBlock
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多