DSCResources/POSHOrigin_vSphere_VM/Helpers/_NewCIMSession.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

function _NewCIMSession {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory)]
        [string]$IPAddress,

        [Parameter(Mandatory)]
        [pscredential]$Credential
    )

    # Establish a CIM session
    $sessionParams = @{
        ComputerName = $IPAddress
        Credential = $Credential
        Verbose = $false
    }
    $cim = New-CimSession @sessionParams

    if ($cim) {

        $ciParams = @{
            ClassName = 'Win32_OperatingSystem'
            Verbose = $false
            ErrorAction = 'SilentlyContinue'
        }
        # Verify this session works by executing a query.
        $os = Get-CimInstance -CimSession $cim @ciParams

        if ($os) {
            # This CIM session works
            Write-Debug -Message 'Successfully established CIM session'
            return $cim
        } else {
            Write-Debug -Message 'Unable to establish CIM session. Trying again using DCOM'
            # On Windows 2008, we may have to use the DCOM session option
            $cim | Remove-CimSession -Verbose:$false
            $sessionParams.SessionOption = New-CimSessionOption -Protocol Dcom
            $cim = New-CimSession @sessionParams
            if ($cim) {
                $os = Get-CimInstance -CimSession $cim @ciParams
                if ($os) {
                    Write-Debug -Message 'Successfully established CIM session using DCOM option'
                    return $cim
                } else {
                    $cim | Remove-CimSession -Verbose:$false
                    Write-Error -Message 'Unable to establish CIM session with DCOM option'
                }
            } else {
                Write-Error -Message 'Unable to establish CIM session with DCOM option'
            }
        }
    } else {
        Write-Error -Message 'Unable to establish CIM session'
    }
}