Call powershell function in a file without a point source

Is this possible if I have only one function in a file with a name similar to the file? I think I remember reading about it before. Something like that:

hello.ps1

function hello { Write-Host 'Hello, world' } 
+4
source share
2 answers

I would generally get rid of the function call. You do not lose parameter names or cmdlets at all. So:

  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 do it all like this:

 > .hello.ps1 "World" 
+5
source

By default, the hello function will only be available in the script area if you are not using a dot-source script. This means that after the script exits, it is no longer displayed. If you want it to be accessible outside hello.ps1 without a point source, you can declare this function in the global scope:

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

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

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

For more information on powershell areas, check out the help .

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

  Write-Host 'Hello, world' 

Then just name it:

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

All Articles