-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremote-moduling.ps1
More file actions
64 lines (59 loc) · 2.38 KB
/
remote-moduling.ps1
File metadata and controls
64 lines (59 loc) · 2.38 KB
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
function New-ModulePSSession
{
<#
.SYNOPSIS
Create a PS session and load the desired module in it, so we can use all of the goodies from it in the remote session
.EXAMPLE
New-ModulePSSession -Computername server01 -ModulePath 'C:\Temp\MyModule.psm1'
New-ModulePSSession -Computername server01 -ModulePath 'C:\Temp\MyModule.psm1' -SessionName mysession01 -Credential (get-credential)
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][ValidateNotNullorEmpty()][String]$ComputerName,
[Parameter(Mandatory=$true,Position=2,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][ValidateNotNullorEmpty()][System.IO.FileInfo]$ModulePath,
[Parameter(Mandatory=$false,Position=3)][String]$SessionName,
[Parameter(Mandatory=$false,Position=4)][PSCredential]$Credential
)
If(!$SessionName)
{
$SessionName = ('{0}-remoteModuleSession' -f $ComputerName)
}
#Create a pssession towards the remote computer
try{
if($Credential)
{
$Session = new-pssession -name $SessionName -ComputerName $ComputerName -Credential $Credential -errorvariable failedtoSession -ErrorAction Stop
}
else
{
$Session = new-pssession -name $SessionName -ComputerName $ComputerName -errorvariable failedtoSession -ErrorAction Stop
}
if ($failedtoSession)
{
Write-Error ('Failed to establish a session to {0} from {1}' -f $Server.Name, $env:COMPUTERNAME)
Return $false
}
Write-Verbose ('Session {0} generated' -f $Session.Name) -Source ${CmdletName}
}
catch
{
Write-Error ('Unable to remotely connect to server. Please enable ps remoting on {0}' -f $Server.Name)
Return $false
}
#Make the module available for use in the remote session
try
{
Write-Verbose ('Loading module {0} into session {1}' -f $ModulePath, $Session.Name)
$rawModule = get-content $ModulePath -Raw -ErrorAction Stop
$moduleScript = [scriptblock]::Create($rawModule)
Invoke-Command -Session $Session -ScriptBlock $moduleScript -ErrorAction Stop | out-null
}
catch
{
Write-Error ('Unable to load module into the remote session {0}' -f $Server.Name)
Disconnect-PSSession $Session -ErrorAction SilentlyContinue | out-null
Remove-PSSession $Session -ErrorAction SilentlyContinue | out-null
Return $false
}
Return $Session
}