Forum Discussion

Marceepoo's avatar
Marceepoo
Copper Contributor
Nov 15, 2023
Solved

Code func, fnLn so that write-host "fnLn $(varA) = $varA" produces: 'Line No. 5: $(varA) = ABC'

I coded a PowerShell (PS) function as follows on lines 1 -4.  On line 5 of the PS script, I inserted the write-host statement(?)/command(?) shown below. [i.e., I don't know which term I should use he...
  • LainRobertson's avatar
    Nov 15, 2023

    Marceepoo 

     

    While you can't produce the kind of output you're after inline, if you're happy calling out to a utility function to display the information, you can get a little closer.

     

    In the example below, I've using the helper function, Write-VariableDetail, to output the information you originally asked for. As you can see though, you do have to provide parameters to the helper function as there's no way of implicitly knowing what the variable's name and value are otherwise.

     

    Write-VariableDetail will work okay for simple variable types like string, int, Boolean, etc. but I haven't put any effort into "nicely" displaying complex types or arrays. PowerShell will default to a ToString() method if the object has one, and if not, it'll simply display the type name - which will look strange.

     

    Example

     

    function Write-VariableDetail()
    {
        [cmdletbinding()]
        param(
            [parameter(Mandatory=$true)] [string] $Name
            , [parameter(Mandatory=$true)] [string] $Value
        );
    
        Write-Information -MessageData "Line $($MyInvocation.ScriptLineNumber): `$$Name = $Value" -InformationAction:Continue;
    }
    
    function Invoke-MyAmazingFunction()
    {
        $Variable1 = "Whazzup!";
        $Variable2 = "Nutin.";
    
        Write-VariableDetail -Name "Variable1" -Value $Variable1;
        Write-VariableDetail -Name "Variable2" -Value $Variable2;
    }

     

     

    Output

     

     

    If you don't want to use the helper function approach then that takes you back to my first reply.

     

    Cheers,

    Lain