Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call powershell function in file without dot sourcing

Tags:

powershell

Is this possible if I only have one function in the file named the same as the file? I seem to remember reading about it before. Something like this:

hello.ps1

function hello {
    Write-Host 'Hello, world'
}
like image 690
Caleb Jares Avatar asked Jul 10 '12 19:07

Caleb Jares


2 Answers

I would get rid of the function call altogether. You don't lose named parameters and cmdlet wrapping at all. So this:

 function Hello
 {
    [CmdletBinding()]
    param(
       [Parameter(Mandatory=$true)]
       $Message
    )
    Write-Host "Hello, $Message!"
 }

becomes:

 [CmdletBinding()]
 param(
    [Parameter(Mandatory=$true)]
    $Message
 )
 Write-Host "Hello, $Message!"

And you can all it like this:

> .hello.ps1 "World"
like image 130
Aaron Jensen Avatar answered Nov 14 '22 01:11

Aaron Jensen


By default, the function hello will only be accessible at script scope unless you dot-source the script. That means, once the script exits, it is no longer visible. If you want it available outside of hello.ps1 without dot-sourcing, you can declare the function at global scope:

function global:hello {
    Write-Host 'Hello, world' 
}

Then you can just execute the script and then call the function:

PS C:\temp> .\hello.ps1
PS C:\temp> hello
Hello, world

For more info on powershell scopes, check out the help.

If you want to just have the code in the function execute, just don't surround it by a function declaration. In hello.ps1:

    Write-Host 'Hello, world' 

Then just call it:

PS C:\temp> .\hello.ps1
Hello, world
like image 40
zdan Avatar answered Nov 14 '22 01:11

zdan