Public/New-PsRemoteSession.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function New-PsRemoteSession {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        "PSUseShouldProcessForStateChangingFunctions", 
        "", 
        Justification = "Object is only created in memory"
    )]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        "PSAvoidUsingPlainTextForPassword", 
        "CredentialName", 
        Justification = "CredentialName only refers to an entry in CredentialStore"
    )]
    <#
    .SYNOPSIS
    XXX

    .DESCRIPTION
    XXX

    .PARAMETER ComputerName
    Hyper-V host

    .PARAMETER CredentialName
    Name of credential

    .PARAMETER UseCredSsp
    Whether the connection uses CredSSP

    .EXAMPLE
    New-PsRemoteSession -ComputerName hv-01

    .EXAMPLE
    New-PsRemoteSession -ComputerName hv-01 -CredentialName 'administrator@example.com'

    .EXAMPLE
    New-PsRemoteSession -ComputerName hv-01 -CredentialName 'administrator@example.com' -UseCredSsp

    .NOTES
    This cmdlet relys on the credential cmdlets of this module
    #>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.Runspaces.PSSession])]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ComputerName
        ,
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]
        $CredentialName
        ,
        [Parameter()]
        [switch]
        $UseCredSsp
    )

    if ($UseCredSsp -And -Not $CredentialName) {
        throw ('[{0}] When using CredSSP credentials must be specified. Aborting.' -f $MyInvocation.MyCommand)
    }

    $params = @{}
                           $params.Add('ComputerName',    $ComputerName)
    if ($CredentialName) { $params.Add('Credential',      (Get-CredentialFromStore -CredentialName $CredentialName)) }
    if ($UseCredSsp)     { $params.Add('Authentication', 'Credssp') }

    $Session = New-PSSession @params
    if (-Not $Session) {
        throw ('[{0}] Failed to create PowerShell remote session to <{1}>. Aborting.' -f $MyInvocation.MyCommand, $ComputerName)
    }

    $Session
}