-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSend-FunctionToPsSession.ps1
52 lines (47 loc) · 1.58 KB
/
Send-FunctionToPsSession.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
Function Send-FunctionToPsSession() {
<#
.SYNOPSIS
Allows use of a local function remotely, in a PsRemoting ScriptBlock
.DESCRIPTION
Allows use of a local function remotely, in a PsRemoting ScriptBlock
.EXAMPLE
$sess = New-PsSession "wsus01" -Cred $Cred
Send-FunctionToPsSession -FunctionName 'Get-SomethingCustom' -Session $sess
$SB = {Get-SomethingCustom -Param 'item1'}
$result = Invoke-Command -Session $sess -ScriptBlock $SB
$sess | Remove-PsSession
.NOTES
Borrowed from:
https://matthewjdegarmo.com/powershell/2021/03/31/how-to-import-a-locally-defined-function-into-a-remote-powershell-session.html
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[System.String[]]
$FunctionName,
[Parameter(Mandatory)]
[System.Management.Automation.Runspaces.PSSession]
$Session
)
Begin {}
Process {
$FunctionName | Foreach-Object {
try {
$Function = Get-Command -Name $_
If ($Function) {
$Definition = @"
$($Function.CommandType) $_() {
$($Function.Definition)
}
"@
Invoke-Command -Session $Session -ScriptBlock {
Param($LoadMe)
. ([ScriptBlock]::Create($LoadMe))
} -ArgumentList $Definition
}
} catch [CommandNotFoundException] {
Throw $_
}
}
}
}#END: Send-FunctionToPsSession