MaximeZ
MaximeZ

Reputation: 13

Powershell running command after script

I'm new to PowerShell and I'm trying to save few clicks by creating a script for daily tasks (Get Username, Reset Password and Unlock Account).

Here is the issue: When I'm launching my script, Powershell will execute everything except cmdlets and will finish by them.

For instance, when I'm using the first choice (Get username ) it will prompt me the "Press enter to end the script" and then display the result of my GetUserName Function.

Please find my code below :

# Author : Maxime
# Creation date :  20/06/2018
# Version : 0.1
Function GetUserName($name)
{
    $u = 'surname -like "' +$name+ '"'
    $res = Get-ADUser -Filter $u | select Name, GivenName, Surname
    return $res
}


echo "Menu"
echo "------"
$choix = read-host " 1. Trouver utilisateur par nom `n 2. Reset Password `n 3. Deverrouiller compte `nChoix  "


if($choix = 1)
{
    $name = Read-Host "Entrez nom utilisateur "
    GetUserName($name)

}
elseif( $choix = 2) 
{
    $id = Read-Host "Entrez ID"
    Set-ADAccountPassword $id -confirm -Reset
}
elseif ($choix -= 3)
{
    $id = Read-Host "Entrez ID "
    Unlock-ADAccount -Confirm $id
}
else
{
    echo "Mauvais choix"
}



read-host "Press enter to end the script ..."

Edit:

When I'm launching the script without ISE:

enter image description here

And when I'm launching the script with the ISE, I can see that my result is displayed after the confirmation to close.

I would like the script to Display the information and then displaying the confirmation to close the window.

enter image description here

Upvotes: 1

Views: 638

Answers (1)

Robert Dyjas
Robert Dyjas

Reputation: 5227

To ensure that output is displayed before prompt from Read-Host you can use:

$res = GetUserName($name)
$res | Format-Table

Very likely it's related with some delay from Select-Object function (also reported here).

Another option is to change this line

$res = Get-ADUser -Filter $u | select Name, GivenName, Surname

to

$res = Get-ADUser -Filter $u | fl Name, GivenName, Surname

When you use Format-List or Format-Table there's no delay and your output is displayed in correct order.

Upvotes: 2

Related Questions