Need to minimize a particular window - powershell

I had tried with below script. While using the below command it will minimize all opened applications. I need minimize only the policy updating window only(Gpupdate.exe). please find the attached gpupdate windows screenshots.
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "gpupdate.exe"
Start-Sleep -s 1
$shell = New-Object -ComObject "Shell.Application"
$shell.minimizeall()

Check out Set-WindowState.ps1 at https://gist.github.com/Nora-Ballard/11240204
It utilizes user32.dll ShowWindowAsync function.
After dot sourcing the function, I can use this in a script:
Get-Process -ID $PID | Set-WindowState -State MINIMIZE
Start-Sleep 3
Get-Process -ID $PID | Set-WindowState -State RESTORE
As long as my script is running within its own window this works. You need to have the process that is the window you want to minimize.

When using Windows 11 (and the Windows Terminal), this script may not work properly with using $PID.
To minimize the Windows Terminal, use
(Get-Process | Where-Object {$_.name -Match 'Terminal'}) | Set-WindowState -State MINIMIZE
The problem is, that it minimizes all Windows Terminal windows.

Related

Powershell Stop-Process Many Instances

I have a remote access program that does not clean up after itself after it is closed. In Task Manager, I oftentimes find 5 to 10 instances of the program running. For instance:
XYZ.exe
XYZ.exe
XYZ.exe
XYZ.exe
XYZ.exe
I have a simple Powershell script to stop these processes, but the problem is I want to close n-1 out of n processes.
> Stop-Process -Force -Name XYZ*
kills n out of n processes.
Is there a way to kill all processes of a program while leaving open the newest (e.g. XYZ.exe #5)?
Use Get-Process to discover all matching processes ahead of time, then simply remove one of them before killing the rest:
Get-Process -Name XYZ* |Select -Skip 1 |Stop-Process -Force
Try this: it closes all non responding processes
Get-Process -name XYZ.exe| Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process

Wait for an Active Directory query to finish before executing next line

Trying to work out how I can make the below code:
Wait for line 1 to complete before continuing.
Wait for line 4 to complete before running line 5
.
$invokevar = Get-ADComputer -Filter * -SearchBase $searchbase | select -Expand dnshostname
New-Variable -name "invoke$dom" -value $invokevar -Force
$fullvar = Get-Variable -Name "invoke$dom" -ValueOnly
$results = Invoke-Command -ComputerName $fullvar -ScriptBlock $sbmain
$badhosts = Compare-Object $($invokevar | Sort-Object) $($results | select -expand pscomputername | Sort-Object) | select -expand InputObject
Having a mental block, any help would be appreciated.
In powershell, the script executes line by line
Unless or until the execution of line 1 finishes, the script wont go for line 2.
So ideally you shouldn't be worrying about the problem stated above.
For internal commands PowerShell does wait before starting the next command. One exception to this rule is external Windows subsystem based EXE applications, you can apply out-null
PowerShell will wait until the exe process has been exited before continuing.
You can also use Start-Process with the -Wait parameter:
Start-Process <path to exe> -NoNewWindow -Wait
If you are using the PowerShell Community Extensions version it is:
$proc = Start-Process <path to exe> -NoWindow
$proc.WaitForExit()
Another option in PowerShell 2.0 is to use a background job:
$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job
In your case it will wait for the execution to get completed. Else you can check the status using a do-While loop and keep on adding a start-sleep of 1 sec
Hope this approach helps you.
Those answers are wrong. Get-ADUser absolutely may return data in the middle of the script down the line..
Some get-aduser command
echo "some string"
I have seen output line 2 first and then the results from line 1.
The only way around this is to assign a variable to the query and process the variable.
$string = get-aduser....
process $string
echo "some string"
This will process in order 1,2,3 without failure.

How to disable touch screen of laptops using PowerShell script?

My clients are using "HP Elitebook 840" touch screen laptop and recently we launched a website for their service, unfortunately click events on buttons did not worked in the web site. After a long R&D we realized it was touch screen issue and mouse click events started working after disabling it.
More info here: Click events are not working in Chrome, but event fires when we execute it manually from console
Since there are more than 40 users having same touch screen laptops, we would like to run a script to disable the touch feature of these laptops. I think network admin needs to run powershell script to do it, but I could not figure it out how to write single script to disable the touch screen of systems
I was reading http://www.surfaceforums.net/threads/disable-the-touch-screen-to-use-the-pen.12338/ but since I am new to PowerShell so need more detailed steps.
Powershell nuggets to disable/enable laptop touch screen. Tested in Windows 10 on Asus UX 501. Run as administrator.
Get-PnpDevice | Where-Object {$_.FriendlyName -like '*touch screen*'} | Disable-PnpDevice -Confirm:$false
Get-PnpDevice | Where-Object {$_.FriendlyName -like '*touch screen*'} | Enable-PnpDevice -Confirm:$false
(Source)
Use this in PowerShell:
Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Wisp\Touch -Name TouchGate -Value 0 -Type DWord
Restart machine after.
You can use the following registry key to disable touch input (requires a reboot):
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Wisp\Touch]
"TouchGate"=dword:00000000
Or with PowerShell:
Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Wisp\Touch ompany -Name TouchGate -Value 0 -Type DWord
After some trial and error, I decided the best thing for me was to save two .bat files to handle this so that I could easily launch it using Launchy. Code below - you might need to add in logic to for the ExecutionPolicy based on your configuration, but works for me as written.
Copy this into notepad and save it as a .bat - just switch out "Disable" for "Enable" and you're good to go either direction
#ECHO off
Powershell.exe -Command "& {Start-Process Powershell.exe -ArgumentList '-Command ""& {Get-PNPDevice | Where-Object FriendlyName -Like ''*touch screen*'' | Disable-PNPDevice -Confirm:$false} ; Get-PNPDevice | Where-Object FriendlyName -Like ''*touch screen*'' ; if ($Host.Name -eq ''ConsoleHost'') {Write-Host ''Press any key to continue...'' ; $Host.UI.RawUI.FlushInputBuffer() ; $Host.UI.RawUI.ReadKey(''""NoEcho,IncludeKeyUp''"") > $null}""' -Verb RunAs}"
I found this question and saw the answers, which are good. However, I found that I didn't want two different scripts to enable/disable the touch screen. I wanted to have it under one to just toggle it's state, so I wrote this script:
# To allow script to be executed on double click
# https://stackoverflow.com/a/30644946/1366368
# To sign script
# https://adamtheautomator.com/how-to-sign-powershell-script/
# To automatically elevate script to admin privs, I used this code fromn https://superuser.com/a/532109/222708
param([switch]$Elevated)
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated) {
# tried to elevate, did not work, aborting
} else {
# Removed -noexit as it will force the powershell instance to keep running after finishing
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
# If Status of touch screen is Error, then it is off.
$result = (Get-PnpDevice|Where-Object {$_.FriendlyName -like '*touch screen*'}|Select -ExpandProperty 'Status')
if ($result -eq 'Error') {
Write-Host "Enabling touch screen"
Get-PnpDevice|Where-Object {$_.FriendlyName -like '*touch screen*'}|Enable-PnpDevice -Confirm:$false
} else {
Write-Host "Disabling touch screen"
Get-PnpDevice|Where-Object {$_.FriendlyName -like '*touch screen*'}|Disable-PnpDevice -Confirm:$false
}

PowerCLI: Task Automation

I have a script that I want to make automatically run every Monday and Thursday each week. I was curious how if it is possible to do this on PowerCLI or if I would have to create a .bat to accomplish this goal. I did some searching and learned that this piece of code was necessary in my script at the top of the line:
add-pssnapin VMware.VimAutomation.Core # <----------
$server = $args[0]
$date = get-date
new-snapshot -vm $server -name "Auto Created via Powershell" -description $date
get-snapshot -vm $server | sort -property created -desc | select -skip 6 | foreach-object{remove-snapshot $_ -confirm:$false}
What else would I need to get this code to run every Monday and Thursday?
Thanks!
EDIT: Where would I edit the task scheduler in order to allow this to run? I've provided an image of where I'm at (that and I'm also a visual person :P )
Why not just using the Task Scheduler of Windows to execute your script as:
powershell.exe -file yourscript.ps1
use powershell /? to kown more options

Kill process by filename

I have 3 instances of application running from different places. All processes have similar names.
How can I kill process that was launched from specific place?
You can get the application path:
Get-Process | Where-Object {$_.Path -like "*something*"} | Stop-Process -WhatIf
That will work for the local machine only. To terminate remote processes:
Get-WmiObject Win32_Process -Filter "ExecutablePath LIKE '%something%'" -ComputerName server1 | Invoke-WmiMethod -Name Terminate
I would like to slightly improve Shay Levy's answer, as it didn't work work well on my setup (version 4 of powershell)
Get-Process | Where-Object {$_.Path -like "*something*"} | Stop-Process -Force -processname {$_.ProcessName}
You can take a look at the MainModule property inside of the Process class (which can be invoked via powershell).
foreach (Process process in Process.GetProcesses())
{
if (process.MainModule.FileName == location)
{
process.Kill();
}
}
I'd also consider the possible exceptions that can occur while calling this code. This might occur if you're trying to access processes that are no longer present (killed since the last time GetProcess was called) or processes for while you do not have permissions.
Try this:
http://technet.microsoft.com/en-us/library/ee177004.aspx
Stop-Process -processname notepad
The below command kills processes wherein "something" is part of the path or is a command line parameter. It also proves useful for terminating powershell scripts such as powershell -command c:\my-place\something.ps1 running something.ps1 from place c:\my-place:
gwmi win32_process | Where-Object {$_.CommandLine -like "*something*"} | % { "$(Stop-Process $_.ProcessID)" }
The solution works locally on my 64bit Windows 10 machine.