Search code examples
powershellazure-powershell

Not getting return value from PowerShell function


I'm trying to clean up some PowerShell scripts and I'm moving inline functions into their own files. I'm not getting the return value when using the file-based approach.

The function I'm using is

function IsModuleInstalled
{
    param
    (
        [string]$moduleName
    )
    if(Get-Module -ListAvailable -Name $moduleName)
    {
        Write-Host "$moduleName Module is installed"
        return $true
    }
    else
    {
        Write-Host "$moduleName Module is not installed"
        return $false
    }
}

When it's left as an inline function then it returns a true/false value.

$val = IsModuleInstalled -moduleName "module"
Write-Host "val = $val" # "val = False"

When I move it to its own file and use dot sourcing I'm not getting a value.

$val = . $PSScriptRoot\..\Functions\IsModuleInstalled.ps1; IsModuleInstalled -ModuleName "module"
Write-Host "val = $val" # "val = "

I've tried using return and Write-Output. How can I fix this?


Solution

  • When you move your function to its own file and then dot-source it, you're essentially importing the function into your current session or script. The dot-sourcing itself doesn't execute the function; it just makes the function available to be called. When you dot-source and then immediately try to execute the function, the return value of the dot-sourcing (which is nothing) is being assigned to $val, not the return value of the function.

    To Fix it:

    1. First, dot-source the file to import the function.
    2. Then, call the function and capture its return value.

    corrected code:

    # Dot-source the function file to import the function
    . $PSScriptRoot\..\Functions\IsModuleInstalled.ps1
    
    # Now call the function and capture its return value
    $val = IsModuleInstalled -ModuleName "module"
    
    Write-Host "val = $val"
    

    This way, the function's return value will be correctly assigned to $val.