0

我有一个有效的 PowerShell 脚本,用于安装当前显示可在 SCCM 客户端中安装的任何补丁,但我发现无法构建一个纠缠测试来验证脚本是否按预期工作而无需实际安装补丁。

是否有一个虚拟补丁以某种方式创建、安装、测试,然后在纠缠测试结束时卸载?我不知道这是否可能。

安装可用补丁的脚本:

Function Install-SCCMAvailablePatches {
  [CmdletBinding()]
  param(
    [Parameter( 
      Mandatory = $False,
      ValueFromPipelineByPropertyName = $True,
      HelpMessage = "Reboot Server if needed? Default: True")]
    [ValidateNotNullOrEmpty()]
    [string]
    $Reboot = $True
  )

  begin {
    Write-Verbose "Install-SCCMAvailablePatches: Started"
  }

  process {
    try {  ([wmiclass]'ROOT\ccm\ClientSDK:CCM_SoftwareUpdatesManager').InstallUpdates([System.Management.ManagementObject[]] (Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -namespace 'ROOT\ccm\ClientSDK')) 
        while (Not((Get-WmiObject -Namespace 'ROOT\ccm\ClientSDK' -Class 'CCM_ClientUtilities' -list).DetermineIfRebootPending().RebootPending)) {
            $Time = (get-date).ToShortTimeString()
            Write-Verbose "Still Patching @ $Time"
            Start-Sleep -s 60 }
        if ($Reboot -eq $True) {
            if ((Get-WmiObject -Namespace 'ROOT\ccm\ClientSDK' -Class 'CCM_ClientUtilities' -list).DetermineIfRebootPending().RebootPending) {
               (Get-WmiObject -Namespace 'ROOT\ccm\ClientSDK' -Class 'CCM_ClientUtilities' -list).RestartComputer()
            }      
        }
    }
    catch {
      Write-Error -Message "Something went wrong with Install-SCCMAvailablePatches."
    }
  }

  end {
    Write-Verbose "Install-SCCMAvailablePatches: Completed"
  }      
} #End Install-SCCMAvailablePatches
4

1 回答 1

0

您应该首先重新编写函数以将其打开以进行测试。 Pester鼓励测试驱动开发,这意味着您定义输入,定义输出,编写测试以确保这些结果,然后编写代码。

Function Install-SCCMAvailablePatches
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [ValidateScript({
            <# Test conditions #>
        })]
        [System.Management.ManagementObject]$UpdateManager,
        [Switch]$Reboot
    )

    Begin
    {
        Write-Verbose "Install-SCCMAvailablePatches: Started"
    }

    Process
    {
        Try
        {
            $UpdateManager.InstallUpdates(
                @(Get-WmiObject -Query 'SELECT * FROM CCM_SoftwareUpdate' -Namespace 'ROOT\ccm\ClientSDK')
            )

            $Client = Get-WmiObject -Namespace 'ROOT\ccm\ClientSDK' -Class 'CCM_ClientUtilities'
            While (-not $Client.DetermineIfRebootPending().RebootPending)
            {
                Write-Verbose (Get-Date -UFormat 'Still patching @ %H:%M')
                Start-Sleep -Seconds 60
            }

            If ($Reboot -and $Client.DetermineIfRebootPending().RebootPending)
            {
                $Client.RestartComputer()
            }
        }
        Catch
        {
            Write-Error -Message "Something went wrong with Install-SCCMAvailablePatches."
        }
    }  

    End
    {
        Write-Verbose "Install-SCCMAvailablePatches: Completed"
    }      
}

现在,您可以在 Pester 测试中使用您自己的对象/属性模拟作为参数传递的 wmi 对象。

于 2017-12-01T16:52:07.903 回答