Dino Cinquegrani
Dino Cinquegrani

Reputation: 13

PowerShell function output

I have a PowerShell script that calls a function and sets the results of the function to a variable. Within the function, I am using the $variable | ft to display the contents of a variable in a table and asking the user to select a number that corresponds to the row in the table they want to act on. I am then returning this variable to the object that called the function:

function getusers{
    $users = @()
    $i = 0
    do {
        $user = ""| select Row, Username, Firstname, lastname
        $user.row = $i
        $user.username ="user$i"
        $user.Firstname = "fname$i"
        $user.lastname = "lname$i"
        $users += $user
        $i += 1
    }while ($i -le 5)

    # Actual logic to build the contents of the $users variable here.
    $users | ft -AutoSize
    $selection = Read-Host "Select number for appropriate user"

    # Logic to determine if user selection is a valid number based on the number of rows in the variable.
    $user = $users[$selection]
    $user
}
$selecteduser = getusers

When calling the function and storing the results in a variable the $users | ft does not display in my console. If I just call the function without storing the results in a variable, the console displays the results of $users | ft.

Upvotes: 0

Views: 675

Answers (1)

emanresu
emanresu

Reputation: 974

It sounds like your question is the following:

How can you display the output of Format-Table in the console when you are calling Format-Table inside of a function where the final output of the function is being assigned to a variable?

From the comments it is clear that you do not want to significantly alter your code, and that you do not want to use something like Out-GridView.

In order to achieve this with the smallest change possible you can change your code:

$users | ft

to the following:

$users | ft | Out-Host

This will print the results of Format-Table to the console, and the value at the end of the function

$user

will be assigned to the variable.

It was tested on Windows 7, PowerShell version 4, in both the ISE and running as a script.

Upvotes: 1

Related Questions