windows 7 cmd hide fullscreen window - powershell

I have a cmd countdown script that minimize all windows, but not a fullscreen window (VLC media player). Is it possible to minimize / hide also the fullscreen window?
countdown.cmd
#echo off
set /p countdownminutes="Minutes: "
set /a countdownseconds = countdownminutes * 60
echo COUNTDOWN
echo %countdownminutes% Minutes
timeout /T %countdownseconds% /nobreak
powershell -command "(new-object -com shell.application).minimizeall()"
Please no solutions with third party software.

You could change that last phrase, since this should be the equivalent of minimise all windows. However, in comments you say it is not enough to deactivate VLC in full screen, so I have added that step before your minimizeall.
#echo off
set /p countdownminutes="Minutes: "
set /a countdownseconds = countdownminutes * 60
echo COUNTDOWN
echo %countdownminutes% Minutes
timeout /T %countdownseconds% /nobreak
mshta.exe vbscript:Execute("CreateObject(""SAPI.SpVoice"").Speak(""Minimising"")(window.close)")
mshta.exe vbScript:Execute("CreateObject(""WScript.Shell"").AppActivate(""VLC media player"", 0)(window.close)")
mshta.exe vbScript:Execute("CreateObject(""WScript.Shell"").SendKeys(""{F11}"")(window.close)")
powershell -command "(new-object -com shell.application).minimizeall()"
rem powershell -command "(New-Object -ComObject shell.application).toggleDesktop()"

Related

Batch: How to focus on cmd after task is initialized

Say my program is as follows
#ECHO Off
start "" "Notepad.exe"
pause
After it opens notepad the windows focus is on notepad so whatever I type is on there, but I want the focus to go back to cmd; is this possible? How?
The specific program i'm trying to run it on, is below:
#ECHO OFF
title SortV8
SETLOCAL ENABLEDELAYEDEXPANSION
cd "C:\img\Unsorted"
:SORT
FOR /R %%f IN (*.jpg *.png *.gif *.jpeg) DO (
echo Current file is: %%f
start "" "D:\Downloads\ImageGlass_Kobe_8.6.7.13_x64\ImageGlass.exe" %%f
powershell.exe -NoProfile -Command "(New-Object -ComObject WScript.Shell).AppActivate((Get-CimInstance Win32_Process -Filter \"ProcessId = $PID\").ParentProcessId)"
CHOICE /N /C 1234 /M "PICK A NUMBER (1 (Photo), 2 (Video), or 3(Delete), 4 (Terminate Program)"%1
IF ERRORLEVEL 4 goto END
IF ERRORLEVEL 3 echo "To the trash it goes!" && move %%f "C:\img\Delete"
IF ERRORLEVEL 2 echo "Video" && move %%f "C:\img\Videos"
IF ERRORLEVEL 1 echo "Photo" && move %%f "C:\img\Photos"
taskkill /IM ImageGlass.exe
cls
GOTO SORT
)
:END
taskkill /IM ImageGlass.exe
cls
echo "Goodbye!"
pause
:eol
You can use PowerShell via its CLI to reactivate your console window, but note that the execution overhead is not insignificant.
Note: This solution is not fully robust, but may work well enough in practice:
#ECHO Off
:: Asynchronously launch Notepad, which steals the focus
:: (Notepad becomes the active window).
start "" "Notepad.exe"
:: Reactivate this console window with the help of PowerShell.
powershell.exe -NoProfile -Command "(New-Object -ComObject WScript.Shell).SendKeys('%%{tab}')"
pause
The above simulates user input, namely an Alt-Tab keypress, in order to reactivate the current console window.
This relies on:
Notepad's window already having been activated (which is likely, given the execution overhead of calling powershell.exe)
the user not manually activating other windows while the batch file runs.
The following variant is more robust, but has a prerequisite that is unlikely to be met:
Rather than sending keystrokes, it properly tries to reactivate the current console window via its process ID.
However, this programmatic window activation only succeeds if the effective SPI_GETFOREGROUNDLOCKTIMEOUT value as reported by the SystemParametersInfo WinAPI function WinAPI function in the current OS uses session is 0, which is not the case by default.
While it is possible in principle to set this value to 0 on demand with PowerShell code, executing such code from cmd.exe (a batch file) inexplicably fails with an Access denied error (whereas direct execution of the same code works fine from PowerShell) - I haven't found a way around this (if someone has an explanation or solution, please tell us).
Certain third-party software - notably AutoHotkey - itself sets the value to 0 once it has run in a session, so if you happen to have a run-on-login AutoHotkey script (it doesn't matter what it does), the code below will work. That said, if you have AutoHotkey already installed, you could try to solve the problem at hand with a specific AutoHotkey script.
#ECHO Off
:: Asynchronously launch Notepad, which steals the focus
:: (Notepad becomes the active window).
start "" "Notepad.exe"
:: !! SEE LIMITATION DISCUSSED ABOVE
:: Reactivate this console window with the help of PowerShell.
powershell.exe -NoProfile -Command "$null = (New-Object -ComObject WScript.Shell).AppActivate((Get-CimInstance Win32_Process -Filter \"ProcessId = $PID\").ParentProcessId)"
pause

Is there a way to switch and close a specific tab on Chrome via Command-line or VBScript? [duplicate]

I'm having a little problem about closing gently Chrome in order to automatically clean cache.
I have a website that is not refreshing correctly, but it does if I clean the cache.
For now I have a .bat file with the following code:
taskkill /F /IM chrome.exe /T > nul
del /q "C:\Users\Francisco\AppData\Local\Google\Chrome\User Data\Default\Cache\*"
FOR /D %%p IN ("C:\Users\Francisco\AppData\Local\Google\Chrome\User Data\Default\Cache\*.*") DO rmdir "%%p" /s /q
timeout 8
start chrome --restore-last-session --start-fullscreen
Now, I know that taskkill /F forces the process to close and that works but as soon as Chrome opens, it shows a message that Chrome wasn't closed correctly and asks me if I want to restore the last session.
If i remove the /f option, Chrome doesn't close:
ERROR: the process with PID 8580 (PID secondary process 8896)
Could not finish.
Reason: This process can be terminated only forcibly (with the / F option).
So... I need one of two options;
Is there a way to gently close Chrome like pressing Alt+F4 using CMD or a VBS?2. Is there a way to hide that Chrome restore last session message?
I'd prefer the first option since it's cleaner.
you can use powershell to close all windows with chrome as process name. It won't kill the task but gently close all chrome browser windows, like if you clicked on top-right cross. Here is the command line to put in batch :
powershell -command "Get-Process chrome | ForEach-Object { $_.CloseMainWindow() | Out-Null}"
Refer to the answer of #tuxy42 :
You can write with vbscript to open chrome browser like this : Open_Chrome_Browser.vbs
Set ws = CreateObject("Wscript.Shell")
siteA = "https://stackoverflow.com/questions/62516355/google-chrome-always-says-google-chrome-was-not-shut-down-properly"
ws.Run "chrome -url " & siteA
And if you want to close it safely : safely_close_chrome_browser.vbs
Set ws = CreateObject("Wscript.Shell")
psCommand = "Cmd /C powershell -command ""Get-Process chrome | ForEach-Object { $_.CloseMainWindow() | Out-Null}"""
ws.run psCommand,0,True
Just browse URL
chrome://quit/

Running PowerShell Script in CMD (with popup window)

Hi I normally just right click and edit my scripts, then just run them through PowerShell ISE using the green arrow.
But I have a need to start /wait a script in a batch file. I want my script to run and then have the rest of the batch file to wait till the PowerShell script is closed. (Hence the start /wait)
And it works fine, but my issue is this:
it opens up fine but no matter if I choose the letters by the options or the numbers I set in the choice script it will either restart or close out depending on the choice.
**I had nice pictures to go with this but I don't have enough rep so here is a bit of code :(
powershell.exe Set-ExecutionPolicy -ExecutionPolicy Bypass
#Main Choice Script
$IP = New-Object System.Management.Automation.Host.ChoiceDescription '&Edit IP', 'Change IP
Address'
$Intro= New-Object System.Management.Automation.Host.ChoiceDescription '&Change Introscreen',
'Change Introscreen'
$Gecko = New-Object System.Management.Automation.Host.ChoiceDescription '&Replace Gecko',
'Change Gecko Folder'
$PCName = New-Object System.Management.Automation.Host.ChoiceDescription '&Host Name', 'Fix
Host Name'
$Firewall = New-Object System.Management.Automation.Host.ChoiceDescription '&Firewall
Settings', 'Fix Firewall Setting'
$Close = New-Object System.Management.Automation.Host.ChoiceDescription '&Close', 'Exit'
$options = [System.Management.Automation.Host.ChoiceDescription[]]
($IP,$Intro,$Gecko,$PCName,$Firewall,$Close)
$title = 'IT Tool'
$message = 'What do you want to do?'
$result = $host.ui.PromptForChoice($title, $message, $options,-1)
switch ('$result')
{
0 { "IP" }
1 { "Intro" }
2 { "Gecko" }
3 { "PCName" }
4 { "Firewall" }
5 { "Close" }
}
I cant seem to get the options to function right, I'm thinking:
CMD is too basic to open a prompt for choice window.
My code isn't setup to run outside ISE
** I'm fine that the cmd window is just text and not a popup, I just would like it to work.
Any help or tips would be appreciated.
As you mentioned you are willing to use batch-file I decided to post an option.
If your options are single commands per entry (or if you are willing to chain commands) you can preset the commands and use choice to select the option.
Note! Here I added some dummy commands to demonstrate how it works:
#echo off & cls
setlocal enabledelayedexpansion
set "sel="Edit IP","Change Introscreen","Replace Gecko",Hostname,Firewall,Close"
set "opt_1=ping localhost"
set "opt_2=echo something"
set "opt_3=echo Replace command here"
set "opt_4=hostname"
set "opt_5=echo firewall command here"
set "opt_6=exit /b"
:menu
set cnt=
for %%i in (%sel%) do (
set /a cnt+=1
echo !cnt!^) %%~i
set "_opt!cnt!=%%~i"
)
for /l %%c in (1,1,%cnt%) do set ch=!ch!%%c
choice /C %ch% /M "Enter Selection:"
echo You chose !_opt%errorlevel%!
!opt_%errorlevel%!
pause
set ch= & cls & goto :menu
You could of course just use a plain text menu directly in your batch file, by using the built-in choice.exe utility.
#Echo Off
:Menu
ClS
Echo 1. Edit IP
Echo 2. Change Introscreen
Echo 3. Replace Gecko
Echo 4. Host Name
Echo 5. Firewall
Echo 6. Close
%SystemRoot%\System32\choice.exe /C 123456 /M "What do you want to do"
GoTo Item%ERRORLEVEL%
:Item1
Echo Changing IP Address
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item2
Echo Changing Introscreen
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item3
Echo Changing Gecko Folder
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item4
Echo Fixing Host Name
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item5
Echo Fixing Firewall Setting
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
GoTo :Menu
:Item6
Echo Exiting
%SystemRoot%\System32\timeout.exe /T 2 1>NUL
Exit /B

Batch - minimize window while running a loop command (not start minimized)

I'm wondering if there is a way to minimize a batch window after it runs a certain command. I already know start /min and tricks to START the window minimized but what about while it's running a loop or timeout?
Let's say:
echo Hello!
timeout /t 100
:COMMAND TO MINIMIZE WINDOW WHILE TIMEOUT IS RUNNING
Right now i'm calling an autoit script in the bat file to hide the window while the command is running with :
WinSetState($application_name, "", #SW_HIDE)
but i'm looking for a pure batch/powershell/vbs solution that can be coded directly in the .bat file.
Thank you for your time!
Use PowerShell's invocation options, executing no command or script.
#echo off & setlocal
echo Hello!
powershell -window minimized -command ""
timeout /t 100
powershell -window normal -command ""
FWIW, -window hidden is also available if you wish.
You can also minimize all windows by using below code with powershell.
$shell = New-Object -ComObject "Shell.Application"
$shell.minimizeall()
Check:
https://techibee.com/powershell/powershell-minimize-all-windows/1017
You can minimize the command prompt on during the run but you'll need two additional scripts: windowMode and getCmdPid.bat:
#echo off
echo Hello!
call getCmdPid >nul
call windowMode -pid %errorlevel% -mode minimized
timeout /t 100
call getCmdPid >nul
call windowMode -pid %errorlevel% -mode normal
This will do. You need to however run the minimize before the timeout as it is in batch. Timeout will now occur once the window is minimized. This example will keep the window during the ping so you can see it minimizes.
echo Hello!
ping 127.0.0.1
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
timeout /t 100
exit

Powershell v2 - Installing Printer

I'm trying to automate printer installation on windows 7 x64, by using Powershell script. So far I have a script that successfully creates TCP/IP port but gives me an error - The arguments are invalid, when it executes printer installation part of the code. Any ideas on how to fix the problem and successfully install a printer through the Powershell? The code is as follows:
$hostAddress = "172.16.2.24"
$portNumber = "9100"
$computer = $env:COMPUTERNAME
$wmi= [wmiclass]"\\$computer\root\cimv2:win32_tcpipPrinterPort"
#$wmi.psbase.scope.options.enablePrivileges = $true
$newPort = $wmi.createInstance()
$newPort.hostAddress = $hostAddress
$newPort.name = "IP_" + $hostAddress
$newPort.portNumber = $portNumber
$newPort.SNMPEnabled = $false
$newPort.Protocol = 1
$newPort.put()
CMD.EXE /C "printui.exe /if /b "Test Printer" /f C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf /r "IP_172.16.2.24" /m "HP Laser Jet P3015""
Question Update: This is the working CMD code, so how do I incorporate it into the Powershell code above ?
printui.exe /if /b "HP Universal Printing PCL 6" /f "C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf" /u /r "IP_172.16.2.24" /m "HP Universal Printing PCL 6"
To embed double-quotes within a double-quoted string you need to escape them. Since you are not using variables, it is easier to use a single quoted string e.g.:
CMD.EXE /C 'printui.exe /if /b "Test Printer" /f C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf /r "IP_172.16.2.24" /m "HP Laser Jet P3015"'
If you ever need to use PowerShell variables inside this string, then you will need to switch back to double quotes and escape the necessary DQ characters e.g:
CMD.EXE /C "printui.exe /if /b `"$PrinterName`" /f C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf /r `"IP_172.16.2.24`" /m `"HP Laser Jet P3015`""
Sorry, but im not sure why you are calling CMD /C #PARAMS. I am just calling the printui.exe directly and it is working, and I only double quote the Args
# Printer Info, I keep this in an SQL DB, and return these values with a query:
$printerID = "<PrinterNameOrID>"
$printerIP = "<PrinterIP>"
$printerPort = "IP_$printerIP"
$printerModel = "<PrinterModelFromINF>"
$driverINFPath = "<UNCPathToDriverINF>"
# Build a new Local TCP Printer Port, naming it with values unique to the Printer ID:
$newPort = ([wmiclass]"Win32_TcpIpPrinterPort").CreateInstance()
$newPort.HostAddress = $printerIP
$newPort.Name = $printerPort
$newPort.PortNumber = "9100"
$newPort.Protocol = 1
$newPort.Put()
# Add the printer
printui.exe /if /b "$printerID" /f "$driverINFPath" /u /r "$printerPort" /m "$printerModel"
I know this has already been answered but you could borrow the code I have in this Excel Workbook (there is a link in the article). I realize it uses VBS but these are built in scripts in Windows and cutting / pasting into Excel has saved me many times and I've installed thousands of printers this way
best-tool-for-printer-creation-excel-vs-print-management-console
Try this:
runas /user:Contoso.com\user1 "printui.exe /if /b \"Test Printer\" /f \"C:\inetpub\wwwroot\ftp\Prdrivers\HP Universal Print Driver\pcl6-x64-5.7.0.16448\hpbuio100l.inf\" /r \"IP_172.16.2.24\" /m \"HP Laser Jet P3015\""