Search code examples
powershellinvoke-command

Close PS1 after passing argu to second ps1 file via invoke-expression


I have GUI that has many function on but one thing i need to build in to it is the staff id number of the member of staff using it so i can add other features. i am trying to do this by creating a login box.(there is no need for password)

my first PS1 opens and gives an input box and then i call the second with invoke-expression and pass the staff id number in an argu.

My problem is that the first PS1 file stay open and wont close untill i close the second. I want it to close after login and just leave me with the second one running

This is my login.ps1

Add-Type -AssemblyName System.Windows.Forms
$form = New-Object Windows.Forms.Form
$form.Size = New-Object Drawing.Size @(210,75)
$form.StartPosition = "CenterScreen"
$Form.Text = "Please Login"


$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Size(5,5) 
$Label.Size = New-Object System.Drawing.Size(55,20) 
$Label.Text = "Staff no:"
$Form.Controls.Add($Label) 

$numInputBox = New-Object System.Windows.Forms.TextBox
$numInputBox.Location = New-Object System.Drawing.Size(60,5) 
$numInputBox.Size = New-Object System.Drawing.Size(50,26) 
$numInputBox.text = ""
$numInputBox.add_Keydown({if ($_.KeyCode -eq "Enter") 
    {login}})
$form.Controls.Add($numInputBox)


Function login {
$sdnum = $numInputBox.text

Invoke-Expression "C:\servicedesk\sdtool.ps1 '$sdnum'"

}

$loginbutton = New-Object System.Windows.Forms.Button
$loginbutton.Size = New-Object System.Drawing.Size(75,21)
$loginbutton.Location = New-Object System.Drawing.Size(115,4)
$loginbutton.add_click({login})
$loginbutton.Text = "Login"
$form.Controls.Add($loginbutton)

$drc = $form.ShowDialog()        

sdtool.ps1 (the sdtool.ps1 is much bigger with many tabs im just using the below to test)

param(
[string]$a
)
Write-host $a

Solution

  • A script won't continue until the cmdlet is done. When you use Invoke-Expression, it won't jump to the next command until the subscript is done (which also runs inside your mainscript's process).

    You could start the second script as a new process so they will run seperately, and then close the login-form so the first script will finish and exit.

    Function login {
    
        $sdnum = $numInputBox.text
    
        Start-Process "powershell.exe" -ArgumentList "-File C:\servicedesk\sdtool.ps1 -a $sdnum"
    
        #Close login-form so the first script will finish.
        $form.Close()
    
    }