Powershell hide all windows

Как запустить PowerShell в скрытом режиме

Иногда может потребоваться запустить скрипт PowerShell в скрытом режиме, незаметно для пользователя. Достичь этого можно различными способами, о некоторых я сегодня расскажу.

Способ первый

Начиная со второй версии PowerShell при запуске можно использовать параметр -WindowStyle со значением Hidden. Это позволяет осуществить запуск в скрытом режиме, без открытия консоли. Предположим, что у меня в папке C:\Temp лежит скрипт hello.ps1, который надо ″по тихому″ выполнить при входе пользователя. Для этого используем следующую команду:

powershell.exe -nologo -noninteractive -windowStyle hidden -command ″C:\Temp\hello.ps1″

Теоретически скрипт должен выполниться в фоне, незаметно для пользователя. Но на практике этот способ работает не всегда, в некоторых случаях во время выполнения скрипта окно PowerShell остается открытым. Поэтому, на всякий случай, рассмотрим еще пару способов запустить PowerShell в скрытом режиме.

Способ второй

Для скрытия окна мы воспользуемся Windows API, точнее функцией ShowWindowAsynс. Первой командой сохраняем сигнатуру C# функции ShowWindowAsync в переменную. Затем с помощью командлета Add-Type добавляем функцию в сеанс в виде статического метода класса. Полученному методу ShowWindowAsync передаем в виде параметров дескриптор окна и цифровое значение, указывающее как должно отображаться окно. Для получения текущего процесса PowerShell используется конструкция Get-Process -Id $pid, дескриптор окна получаем из его свойства MainWindowHandle. В качестве цифрового значения указываем 0 (SW_HIDE), чтобы скрыть окно:

$Signature = @″
[DllImport(«user32.dll»)]public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
″ @
$ShowWindowAsync = Add-Type -MemberDefinition $Signature -Name «Win32ShowWindowAsync» -Namespace Win32Functions -PassThru
$ShowWindowAsync::ShowWindowAsync((Get-Process -Id $pid).MainWindowHandle, 0)

Полученный код добавляем в начало скрипта.

Способ третий

Скрыть запуск PowerShell можно, как ни странно, с помощью VBScript. Для этого создаем vbs-файл следующего содержания:

command = ″powershell.exe -nologo -noninteractive -command C:\Temp\hello.ps1″
set shell = CreateObject(″WScript.Shell″)
shell.Run command,0, false

Цифра 0 в скрипте означает запуск в скрытом виде, false — не ждать окончания выполнения команды.

Теперь для запуска PowerShell скрипта надо запустить этот vbs-файл и он тихо выполнится.

В заключение уточню, что все три способа не могут полностью скрыть запуск скрипта. При запуске все равно видно всплывающее окно. Заметить этот момент сложно, поскольку окно всплывает на доли секунды, но все же можно.

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

I currently open my PowerShell script through a .bat file. The script has a GUI. I tried to put this in my script but it hid the GUI as well and also kept looping because I wanted my GUI to continuously loop:

How do we run a script without Command Promp, but also not hide the gui? And is that the same if we run the script using a .bat file? Thank you!

Читайте также:  Windows powershell windows 10 download

4 Answers 4

If you want to hide the Console behind the GUI I’ve had success with the following native functions:

Once the above functions have been added to your Form, simply call the Hide-Console function in your Form_Load event:

If you need to show the Console, perhaps for debugging, you can easily show the console again by calling the Show-Console function:

For more information on the numbers you can pass to ShowWindow you can check out the ShowWindow documentation on MSDN here

Update based on comment

Thanks for this code. I tried to use it in my script, but where exactly am I suppose to put Hide-Console? My form load looks like this $objForm.Add_Shown(<$objForm.Activate()>) [void] $objForm.ShowDialog()

To hide the console with this code, all you need to do is call Hide-Console . Since you already have code in the Shown event ( $objForm.Add_Shown ) we can simply add another line to call the command:

When your form is Shown the console will be hidden (You can still call Show-Console if you want to see it later).

How to Hide Updates Using PowerShell in Windows 10

Unlike the previous versions of Windows, Microsoft made it a lot harder to manage the updates in all Windows 10 systems. In fact, there are no built-in options to easily hide the unwanted updates. That being said, I’ve already covered how you can manage and disable automatic updates in Windows 10. One way is to use the official troubleshooting app to temporarily hide the updates you don’t want to install.

Alternatively, you can also use Windows PowerShell to hide the unwanted Windows updates. Let me show you how.

Hide Updates Using PowerShell in Windows 10

Before you can use Windows PowerShell to hide the updates, you first need to install the Windows Update PowerShell Module. To do that, head over to the official site and download it.

Once you’ve downloaded the module, open the downloaded zip file, and copy the “PSWindowsUpdate” folder to the following location:

Once you’ve installed the PowerShell module, search for PowerShell in the Start menu, right-click on it and select the option “Run as Administrator.”

By default, your user account will have restricted access, and you won’t be able to run any external scripts in PowerShell. To run external scripts, you need to set the execution policy to Unrestricted. To do that, enter the below command and press the Enter button.

As soon as you execute the command, you will be asked for the confirmation. Simply press the A key and then the Enter button on your keyboard. From this point onward, your user account will have unrestricted access.

If you want to, you can check the current execution policy of your user account using the below command. As you can see, I have unrestricted access.

After changing the execution policy, you are free to use the PowerShell however you want. To start, use the below command to get a list of all the available Windows updates.

Once you have the list of all the available updates, find the update you want to hide and note the title of the update. Enter the following command, and press the Enter button to hide the update. Don’t forget to replace Chicony* with the actual title.

We can use the wildcard (*) before and after the title as long as part of the title is correct and unique. If you don’t want to bother with the wildcards, just enter the full update title.

Now PowerShell wants you to confirm your action. Simply press the A key on your keyboard and press the Enter button.

This action will hide the target Windows Update. You can confirm that by looking at the letter H under “Status.” In case you are wondering, the letter H stands for Hidden .

Alternatively, you can also hide a Windows update using its KB Article ID. To hide a Windows update using its KB Article ID, simply use the command below. Don’t forget to replace the KB Article ID in the below command with the ID of the update you want to hide.

Again, PowerShell will ask you for the confirmation. Enter the letter “A” and press the Enter button.

You’ve successfully hidden the update.

In the future, if you ever want to unhide the update, get the list of all the available updates using Get-WUList and copy the KB Article ID of the update you want to unhide. Use the below command while replacing the KB Article ID with your own and press the Enter button.

The above action will again ask you for the confirmation; simply confirm the action, and you will have your update back.

To wrap it up, change your execution policy back to Restricted using the below command. Having your user account run the scripts with unrestricted access is not good.

Do comment below sharing your thoughts and experiences about using PowerShell to hide updates in Windows 10.

Vamsi is a tech and WordPress geek who enjoys writing how-to guides and messing with his computer and software in general. When not writing for MTE, he writes for he shares tips, tricks, and lifehacks on his own blog Stugon.

5 comments

Great tips and tweaks for Windows 8.1 and 10. Release have delayed installing 10 for a while just to let MS iron out any early bugs and for me to get my backups sorted. Keep up the good work.

“PS C:\Users\Администратор> Set-ExecutionPolicy RemoteSigned

Изменение политики выполнения
Политика выполнения защищает компьютер от ненадежных сценариев. Изменение политики выполнения может поставить под
угрозу безопасность системы, как описано в разделе справки, вызываемом командой about_Execution_Policies. Вы хотите
изменить политику выполнения?
[Y] Да – Y [N] Нет – N [S] Приостановить – S [?] Справка (значением по умолчанию является “Y”): Y
PS C:\Users\Администратор> Import-Module PSWindowsUpdate
PS C:\Users\Администратор> Get-WUInstall -MicrosoftUpdate -ListOnly

ComputerName Status KB Size Title
———— —— — —- —–
WIN-SV4A0… —— KB3068708 383 KB Обновление для Windows 8.1 (KB3068708)

PS C:\Users\Администратор> Hide-WUUpdate

ComputerName Status KB Size Title
———— —— — —- —–
WIN-SV4A0… —H– KB3044374 3 MB Обновление для Windows 8.1 (KB3044374)
WIN-SV4A0… —H– KB3075249 99 KB Обновление для Windows 8.1 (KB3075249)
WIN-SV4A0… —H– KB3080149 702 KB Обновление для Windows 8.1 (KB3080149)

PS C:\Users\Администратор> Hide-WUUpdate -KBArticleID KB3068708
PS C:\Users\Администратор> Get-WUInstall -MicrosoftUpdate -ListOnly

ComputerName Status KB Size Title
———— —— — —- —–
WIN-SV4A0… —— KB3068708 383 KB Обновление для Windows 8.1 (KB3068708)

I have accidentally hidden a chipset update that does not have a KB number. How do i make it visible now? I’m assuming that this is a very important update that i definitely need.

You can use the official Windows tool found in the link below to hide or unhide the updates.
https://support.microsoft.com/en-us/kb/3073930

A great help for me. I have had an issue with a security update for Internet explorer (Flash player) under Win 8.1 leading to let my printer control center crash. The previously mentioned official windows tool does not work under Win 8.1 (only Win 10). So I had to use the method mentioned here and I can confirm that this method works fine also under Win 8.1.

Comments are closed.

6 Ways to Check Hard Disk Health on Windows 10

8 Ways to Quickly Turn Off Your Screen in Windows 10

Latest Windows 10 Update Problems and How to Fix Them

13 Cool 4K Desktop Backgrounds for Windows 10

5 of the Best Ebook Readers for Windows 10

How to Remove Old and Useless Drivers in Windows 10

5 Lightweight Browsers for Windows 10

Find and Open Files Using Command Prompt in Windows 10

How to Increase the Maximum Volume in Windows 10

How to Fix Webcam or Camera Not Working in Windows 10

Affiliate Disclosure: Make Tech Easier may earn commission on products purchased through our links, which supports the work we do for our readers.

Оцените статью