SteveMustafa
SteveMustafa

Reputation: 619

Debugging PowerShell

I'm not certain what is wrong with this scriptlet.

I'm trying to break out functionality into several other functions (I have a programming background not a scripting one per se) and to me LOGICALLY the following should execute starting at the "main" function Test-SgnedMpsPackage, accepting the various optional parameters (the script is not yet complete) then when the function Check-Path is called, that is run, then work would resume in the original calling function.

Am I missing something here? On a side note, how does one return a value to the calling function? a simple return?

function CheckPath($path)
{
    if ( test-path -Path $path ) 
        { Write-Host "{0} confirmed to exist." -f $path }
    else
        { Write-Host "{0} DOES NOT exis.\nPlease check and run the script again" -f $path }
    exit { exit }
}


function Test-SignedMpsPackage 
{
    Param(
        [string] $PkgSource,
        [string] $SigSource,
        [string] $Destination
    )
    Process
    {

        #Check that  both files exist
        Write-Host "Check for file existence..."


        CheckPath($PkgSource)
        CheckPath($SigSource)

        #retrieve signatures from file
    }
}

Upvotes: 0

Views: 68

Answers (1)

Keith Hill
Keith Hill

Reputation: 202052

Unlike C, C++ or C# there is no "main" entry point function. Any script at the top level - outside of a function - executes. You have defined two functions above but you haven't called either one. You need to do something like this:

function Test-SignedMpsPackage 
{
    ...
}

Test-SignedMpsPackage params

Also as mentioned by @Bill_Stewart, you call your defined functions just like you call PowerShell commands - arguments are space separated and you don't use parens except to evaluate an expression inside the parens.

As for returning a value from a function, any output (Output stream) not captured by assigning to a variable or being redirected to a file is automatically part of the function's output. So I would modify your CheckPath function to this:

function CheckPath($path)
{
    if (Test-Path -Path $path) { 
        Write-Verbose "{0} confirmed to exist." -f $path 
        $true
    }
    else { 
        Write-Verbose "{0} DOES NOT exist.\nPlease check and run the script again" -f $path 
        $false
    }
}

You can use Write-Host as you had before but sometimes, perhaps in a script, you don't want to see the extra output. That is where Write-Verbose comes in handy. Set $VerbosePreference = 'Continue' to see the verbose output.

Upvotes: 2

Related Questions