Home > Net >  Powershell -- how to minimize the console the script is running in while sitting in a loop?
Powershell -- how to minimize the console the script is running in while sitting in a loop?

Time:03-10

I have a powershell script that is in my startup:

%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\

Note, the script itself is not in startup. Rather in \Startup\ is a shortcut to the script. The shortcut is to:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoProfile -File C:\develop\utils\powershell\converter.ps1

and it sits in a loop all day, waiting for events. This is the loop:

try {
    # At the end of the script... 
    while ($true) {
        Start-Sleep -Seconds .2
    }    
}
catch {}
Finally {
    # Work with CTRL   C exit too !
    Unregister-Event -SourceIdentifier $eventname 
}

Works great.

But when I log in, there is that command box....

How do I get the script to be exactly what it is, but minimized? (Or even better,,, sit in the tray... but only if that is easy! What I mean here is: Ideally it wouldn't even be in my alt-tab window sequence... but I could terminate it if I needed to....)

I should further note that the script has to be in my user session, as the events it feeds from are triggered by me as I use other apps. (IOW: Putting it in task scheduler is not an option.)

CodePudding user response:

Update: The following instructions work as advertised, but you state that you were aware of this approach, and that your only problem was that the styling of File Explorer's GUI in Windows 11 may falsely suggest that the window-style dropdown list (field Run in a shortcut file's Properties dialog) is disabled.


Here's how to run your script minimized on startup, via the user-specific "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup" folder.

  • Move your script file, say foo.ps1 out of the startup folder,[1] say to your desktop.

  • In its place, create a shortcut file (.lnk) that calls your script file with its window minimized:

    • To do this interactively, via File Explorer's New > Shortcut shortcut-menu command:
      • Paste the following target command and submit:

        powershell.exe -ExecutionPolicy Bypass -File "%USERPROFILE%\Desktop\foo.ps1"  
        
      • Type a file name (.lnk will be appended, though that extension is by default hidden in File Explorer) and submit.

      • Open the Properties dialog for the newly created file and, in field Run, select Minimized, then submit.


[1] As Abraham Zinala points out, .ps1 are not executed by default when placed in the startup folder or double-clicked in File Explorer (instead, they are opened for editing). However, it is possible to reconfigure a system to do that - see this answer. Still, that wouldn't give you control over the script's window state when placed directly in the startup folder.

  • Related