arifr
arifr

Reputation: 53

Run Powershell script to show a form without Powershell screen at the back

I have a powershell script that can be run locally on a Workstation or remotely using PSEXEC tool, that shows a dialog box to console user that the PC is going to be rebooted in X amount of time and timer. The dialog box cannot be closed, only be minimized (this is as per code). However when I run it, it also shows Powershell screen at the back of dialog box and closing it also closes the form.

I tried Powershell switches [-NoLogo], [-NonInteractive], [-WindowStyle Hidden], it doesn't work. enter image description here

This is the custom-restart script:

Function Create-GetSchedTime {   
Param(   
$SchedTime   
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
$Message = "Your computer will automatically restart in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
#$TotalTime = 14400 #in seconds
$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            &schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({
      &schtasks /delete /tn "Post Maintenance Restart" /f
      shutdown -r -f /t 0
      $Form.Close()
})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      #$TotalTime = 3600
      $TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(330,25)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
$Label2 = New-Object -TypeName System.Windows.Forms.Label
$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
$Label2.Text = $Message2
$label2.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
$labelTime.Location = '120, 60'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()

Upvotes: 1

Views: 5351

Answers (2)

arifr
arifr

Reputation: 53

Eventually I found out the issue. I was putting "-WindowStyle Hidden" at the end of command, not after Powershell. So this didn't work.

Powershell -File CustomRestart.ps1 -WindowStyle Hidden

This worked, also with PSEXEC.

Powershell -WindowStyle Hidden -File CustomRestart.ps1

Now I added a YES/No confirmation dialog box after user clicks on "Restart Now" button, if clicks Yes, it will reboot, if no, then nothing, just confirmation box disappears. If you look at the $Button1.Add_Click event, there is the code.

Problem is: when I run it on Pwershell ISE, its doing fine (confirmation box shows-up and works), but when running from Command or Run menu, it won't show confirmation box, and thus no effect after clicking "Restart Now" button.

Here is the complete code:

Function Create-GetSchedTime {   
Param(   
$SchedTime   
)
      $script:StartTime = (Get-Date).AddSeconds($TotalTime)
      $RestartDate = ((get-date).AddSeconds($TotalTime)).AddMinutes(-5)
      $RDate = (Get-Date $RestartDate -f 'dd.MM.yyyy') -replace "\.","/"      # 16/03/2016
      $RTime = Get-Date $RestartDate -f 'HH:mm'                                    # 09:31
      #&schtasks /delete /tn "Post Maintenance Restart" /f
      #&schtasks /create /sc once /tn "Post Maintenance Restart" /tr "'C:\Windows\system32\cmd.exe' /c shutdown -r -f -t 300" /SD $RDate /ST $RTime /f
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic") | Out-Null
$Title = "Computer Reboot Notification"
#$Message = "Your computer will automatically restart in :"
$Message = "Your computer has been updated with latest software and requires a reboot. Please save your work and click ""Restart now"" to reboot it now.`nYour computer will automatically reboot in :"
$Button1Text = "Restart now"
$Button2Text = "Postpone for 1 hour"
$Button3Text = "Postpone for 4 hours"
$Form = $null
$Button1 = $null
$Button2 = $null
$Label = $null
$TextBox = $null
$Result = $null
$timerUpdate = New-Object 'System.Windows.Forms.Timer'
$TotalTime = 14400 #in seconds
#$TotalTime = 60 #in seconds
Create-GetSchedTime -SchedTime $TotalTime
$timerUpdate_Tick={
      # Define countdown timer
      [TimeSpan]$span = $script:StartTime - (Get-Date)
      # Update the display
      $hours = "{0:00}" -f $span.Hours
      $mins = "{0:00}" -f $span.Minutes
    $secs = "{0:00}" -f $span.Seconds
    $labelTime.Text = "{0}:{1}:{2}" -f $hours, $mins, $secs
      $timerUpdate.Start()
      if ($span.TotalSeconds -le 0)
      {
            $timerUpdate.Stop()
            #&schtasks /delete /tn "Post Maintenance Restart" /f
            shutdown -r -f /t 0
      }
}
$Form_StoreValues_Closing=
      {
            #Store the control values
      }

$Form_Cleanup_FormClosed=
      {
            #Remove all event handlers from the controls
            try
            {
                  $Form.remove_Load($Form_Load)
                  $timerUpdate.remove_Tick($timerUpdate_Tick)
                  #$Form.remove_Load($Form_StateCorrection_Load)
                  $Form.remove_Closing($Form_StoreValues_Closing)
                  $Form.remove_FormClosed($Form_Cleanup_FormClosed)
            }
            catch [Exception]
            { }
      }

# Form
$Form = New-Object -TypeName System.Windows.Forms.Form
$Form.Text = $Title
$Form.Size = New-Object -TypeName System.Drawing.Size(407,205)
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $true
$Form.KeyPreview = $true
$Form.ShowInTaskbar = $Formalse
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $Formalse
$Form.MinimizeBox = $true
$Icon = [system.drawing.icon]::ExtractAssociatedIcon("c:\Windows\System32\UserAccountControlSettings.exe")
$Form.Icon = $Icon

# Button One (Reboot/Shutdown Now)
$Button1 = New-Object -TypeName System.Windows.Forms.Button
$Button1.Size = New-Object -TypeName System.Drawing.Size(90,25)
#$Button1.Location = New-Object -TypeName System.Drawing.Size(10,135)
$Button1.Location = New-Object -TypeName System.Drawing.Size(10,145)
$Button1.Text = $Button1Text
$Button1.Font = 'Tahoma, 10pt'
$Button1.Add_Click({

    $msgBoxInput =  [System.Windows.MessageBox]::Show('Are you sure you want to reboot now?','Computer Reboot Confirmation','YesNo','Warning')
    switch  ($msgBoxInput) {
        'Yes' {
            shutdown -r -f /t 0
            $Form.Close() 
              }

        'No' {
          ## Do something
            }
                            }

})
$Form.Controls.Add($Button1)
# Button Two (Postpone for 1 Hour)
$Button2 = New-Object -TypeName System.Windows.Forms.Button
$Button2.Size = New-Object -TypeName System.Drawing.Size(133,25)
#$Button2.Location = New-Object -TypeName System.Drawing.Size(105,135)
$Button2.Location = New-Object -TypeName System.Drawing.Size(105,145)
$Button2.Text = $Button2Text
$Button2.Font = 'Tahoma, 10pt'
$Button2.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 3600
      #$TotalTime = 30
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button2)

# Button Three (Postpone for 4 Hours)
$Button3 = New-Object -TypeName System.Windows.Forms.Button
$Button3.Size = New-Object -TypeName System.Drawing.Size(140,25)
#$Button3.Location = New-Object -TypeName System.Drawing.Size(243,135)
$Button3.Location = New-Object -TypeName System.Drawing.Size(243,145)
$Button3.Text = $Button3Text
$Button3.Font = 'Tahoma, 10pt'
$Button3.Add_Click({
      $Button2.Enabled = $False
      $timerUpdate.Stop()
      $TotalTime = 14400
      Create-GetSchedTime -SchedTime $TotalTime
      $timerUpdate.add_Tick($timerUpdate_Tick)
      $timerUpdate.Start()
})
$Form.Controls.Add($Button3)
$Button3.Enabled = $False

# Label
$Label = New-Object -TypeName System.Windows.Forms.Label
$Label.Size = New-Object -TypeName System.Drawing.Size(380,65)
$Label.Location = New-Object -TypeName System.Drawing.Size(10,15)
$Label.Text = $Message
$label.Font = 'Tahoma, 10pt'
$Form.Controls.Add($Label)

# Label2
#$Label2 = New-Object -TypeName System.Windows.Forms.Label
#$Label2.Size = New-Object -TypeName System.Drawing.Size(355,30)
#$Label2.Location = New-Object -TypeName System.Drawing.Size(10,100)
#$Label2.Text = $Message2
#$label2.Font = 'Tahoma, 10pt'
#$Form.Controls.Add($Label2)

# labelTime
$labelTime = New-Object 'System.Windows.Forms.Label'
$labelTime.AutoSize = $True
$labelTime.Font = 'Arial, 26pt, style=Bold'
#$labelTime.Location = '120, 60'
$labelTime.Location = '120, 90'
$labelTime.Name = 'labelTime'
$labelTime.Size = '43, 15'
$labelTime.TextAlign = 'MiddleCenter'
$labelTime.ForeColor = "Red"
$Form.Controls.Add($labelTime)

#Start the timer
$timerUpdate.add_Tick($timerUpdate_Tick)
$timerUpdate.Start()
# Show
$Form.Add_Shown({$Form.Activate()})
#Clean up the control events
$Form.add_FormClosed($Form_Cleanup_FormClosed)
#Store the control values when form is closing
#$Form.add_Closing($Form_StoreValues_Closing)
$Form.Add_Closing({$_.cancel = $true})
#Show the Form
$Form.ShowDialog() | Out-Null
#$Form.Focused
#return $Form.ShowDialog()

#$Form.Add_Closing({$_.cancel = $false})
#Show the Form
#return $Form.ShowDialog()

Upvotes: 2

wasif
wasif

Reputation: 15470

You need to use .NET for this. Here is a function:

# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

function Show-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    $consolePtr = [Console.Window]::GetConsoleWindow()

    # Hide = 0,
    # ShowNormal = 1,
    # ShowMinimized = 2,
    # ShowMaximized = 3,
    # Maximize = 3,
    # ShowNormalNoActivate = 4,
    # Show = 5,
    # Minimize = 6,
    # ShowMinNoActivate = 7,
    # ShowNoActivate = 8,
    # Restore = 9,
    # ShowDefault = 10,
    # ForceMinimized = 11

    [Console.Window]::ShowWindow($consolePtr, 4)
function Hide-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}

Now call it in the Form_Load event.

$OnFormLoad = 
{
    Hide-Console
}

To show again use Show-Console.

Attribution: Opening PowerShell Script and hide Command Prompt, but not the GUI

Upvotes: 0

Related Questions