Skip to content

Commit 3606c06

Browse files
author
James Brundage
committed
feat: Use-Module ( Fixes #1130 )
1 parent 7878ebd commit 3606c06

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Commands/Module/Use-Module.ps.ps1

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
[ValidatePattern('Use[-\.]Module')]
2+
param()
3+
function Use-Module
4+
{
5+
<#
6+
.SYNOPSIS
7+
Uses a module.
8+
.DESCRIPTION
9+
Uses a module.
10+
11+
This can either:
12+
13+
* Invoke a ScriptBlock in the module's context
14+
* Run a module's `Use` function, if present
15+
* Call a module's `Use` method, if present
16+
17+
In all cases, the script block should be run in the module's context, using dot-sourcing.
18+
.EXAMPLE
19+
Get-Module PipeScript | Use-Module -ScriptBlock { $myInvocation.MyCommand.ScriptBlock.Module }
20+
#>
21+
[Alias('Use.Module','Module.Use')]
22+
param(
23+
# The name of the module
24+
[vfp()]
25+
[Alias('ModuleName')]
26+
[string]
27+
$Name,
28+
29+
# The script block to use.
30+
[ScriptBlock]
31+
$ScriptBlock = {},
32+
33+
[Parameter(ValueFromRemainingArguments)]
34+
[Alias('Arguments','Args')]
35+
[PSObject[]]
36+
$ArgumentList,
37+
38+
[Parameter(ValueFromPipelineByPropertyName)]
39+
[Collection.IDictionary]
40+
$Parameter
41+
)
42+
43+
process {
44+
# Get the piped in object
45+
$pipedIn = $_
46+
# If we have no name, return
47+
return if -not $name
48+
49+
$moduleContext = if ($pipedIn -is [Management.Automation.PSModuleInfo]) {
50+
$name = $pipedIn
51+
$pipedIn
52+
} else {
53+
Get-Module $Name | Select-Object -First 1
54+
}
55+
56+
57+
return if -not $moduleContext
58+
59+
if ($ArgumentList) {
60+
if ($Parameter) {
61+
. $moduleContext $ScriptBlock @ArgumentList @Parameter
62+
} else {
63+
. $moduleContext $ScriptBlock @ArgumentList
64+
}
65+
} elseif ($Parameter) {
66+
. $moduleContext $ScriptBlock @Parameter
67+
} else {
68+
. $moduleContext $ScriptBlock
69+
}
70+
}
71+
}

0 commit comments

Comments
 (0)