Reputation: 141512
A function that I dotted-in to my PowerShell profile is not available during my current session. The function looks like this:
# \MyModules\Foobar.ps1
function Foo-Bar {
Write-Host "Foobar";
}
# Test loading of this file
Foo-Bar;
And my profile looks like this:
# \Microsoft.PowerShell_profile.ps1
Write-Host "Loading MyModules..."
Push-Location ~\Documents\WindowsPowerShell\MyModules
.\Foobar.ps1
Pop-Location
Write-Host "Done"
When I run . $profile
the output looks as follows, which confirms the Foo-Bar
function works.
> . $profile
Loading MyModules...
Foobar
Done
Running the Foo-Bar
function after that, though, explodes like this:
Foo-Bar : The term 'Foo-Bar' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Foo-Bar
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Foo-Bar:String) [],
CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Why isn't it available?
Upvotes: 2
Views: 2870
Reputation: 47387
Well, there are a couple of ways to approach it. Note, neither one of these approaches will require you to dot-invoke your module before importing it.
1) use a proper module MyMethod.psm1
# MyMethod.psm1 (m for module)
function MyMethod {
# my method
}
Export-ModuleMember MyMethod
# then in your profile
Import-Module "MyMethod"
2) if you have a collection of methods and need to break them into multiple files
# MyMethod1.ps1
function Invoke-MyMethod1{
# my method1
}
Set-Alias imm Invoke-MyMethod1
# MyMethod2.ps1
function Something-MyMethod2 {
# my method2
}
Set-Alias smm Something-MyMethod2
# MyMethod.psm1 (m for module)
Push-Location $psScriptRoot
. .\MyMethod1.ps1
. .\MyMethod2.ps1
Pop-Location
Export-ModuleMember `
-Alias @(
'*') `
-Function @(
'Invoke-MyMethod1',
'Something-MyMethod2')
# then in your profile
Import-Module "MyMethod"
Upvotes: 3