-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathUse-Module.ps1
More file actions
77 lines (67 loc) · 2.21 KB
/
Use-Module.ps1
File metadata and controls
77 lines (67 loc) · 2.21 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
65
66
67
68
69
70
71
72
73
74
75
76
77
[ValidatePattern('Use[-\.]Module')]
param()
function Use-Module {
<#
.SYNOPSIS
Uses a module.
.DESCRIPTION
Uses a module's context to run a `[ScriptBlock]` (with dot-sourcing).
.EXAMPLE
Get-Module PipeScript | Use-Module -ScriptBlock { $myInvocation.MyCommand.ScriptBlock.Module }
#>
[Alias('Use.Module','Module.Use')]
param(
# The name of the module
[Parameter(ValueFromPipeline)]
[Alias('ModuleName')]
[string]
$Name,
# The script block to use.
[ScriptBlock]
$ScriptBlock = {},
# The list of arguments to pass to the script block.
[Parameter(ValueFromRemainingArguments)]
[Alias('Arguments','Args')]
[PSObject[]]
$ArgumentList,
# Any named parameters to pass to the script block.
[Parameter(ValueFromPipelineByPropertyName)]
[Alias('Parameters')]
[Collections.IDictionary]
$Parameter
)
process {
# Get the piped in object
$pipedIn = $_
# If we have no name, return
if (-not $name) { return }
# Get the module context
$moduleContext =
# (if it was already piped in, we already have it)
if ($pipedIn -is [Management.Automation.PSModuleInfo]) {
$name = $pipedIn
$pipedIn
} else {
Get-Module $Name | Select-Object -First 1
}
# We're running in the module context,
$runningIn = $moduleContext
# and we want `$toRun` the ScriptBlock.
$ToRun = $ScriptBlock
# The rest of the code is tedium.
# If there were arguments and parameters, pass them both with splatting.
if ($ArgumentList) {
if ($Parameter) {
. $runningIn $ToRun @ArgumentList @Parameter
} else {
. $runningIn $ToRun @ArgumentList
}
} elseif ($Parameter) {
# If there were only parameters, pass them with splatting.
. $runningIn $ToRun @Parameter
} else {
# If there were no arguments or parameters, just run the script block.
. $runningIn $ToRun
}
}
}