Public/Set-PSSession.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
function Set-PSSession {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        "PSUseShouldProcessForStateChangingFunctions", 
        "", 
        Justification = "Only changes default parameters for session cmdlets"
    )]
    [CmdletBinding()]
    param(
        [Parameter(Mandatory,ParameterSetName='CredentialName')]
        [ValidateNotNullOrEmpty()]
        [string]
        $Name
        ,
        [Parameter(Mandatory,ParameterSetName='CredentialFile')]
        [ValidateNotNullOrEmpty()]
        [string]
        $Path
        ,
        [Parameter(Mandatory,ParameterSetName='CredentialObject')]
        [ValidateNotNullOrEmpty()]
        [pscredential]
        $Credential
        ,
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ComputerName
    )

    if ($PSCmdlet.ParameterSetName -ieq 'CredentialName') {
        $Path = Join-Path -Path $PSScriptRoot -ChildPath "$Name.clixml"
    }
    if (-not (Test-Path -Path $Path)) {
        throw ('[{0}] Credential file {0} not found. Aborting.' -f $MyInvocation.MyCommand, $Path)
    }
    $Credential = Import-Clixml -Path $Path
    if (-not $Credential) {
        throw ('[{0}] Failed to import credentials. Aborting' -f $MyInvocation.MyCommand)
    }

    $Session = New-PSSession -ComputerName $ComputerName -Credential $Credential
    if (-not $Session) {
        throw ('[{0}] Failed to create remote session. Aborting.' -f $MyInvocation.MyCommand)
    }
        
    Get-Command -ParameterType PSSession -ParameterName Session | Select-Object -ExpandProperty Name | ForEach-Object {
        $PSDefaultParameterValues."$_:Session" = $Session
    }
}