TASKKILL command works properly outside Script, but not inside of it - windows

Few days ago I started developing a Powershell script which monitors a service. Command:
taskkill /f /fi "USERNAME eq admin" /im tm1top.exe
When I ran taskkill to stop one process inside my script it didn’t work: that process remained in Running, hence the script was not able to end properly.
On the other hand, running exactly the same command (taskkill) from CMD directly was successful.
NOTE: the user which is running this script has ADMIN RIGHTS on the computer and I am running Windows Seever 2008. Also tried to create a task into Windows Scheduler and to run it with highest privileges with this user, but the same result..
Could you please advise what should I modify in order to make this function work directly from my ps script?

I would recommend using WMI for this:
Get-WmiObject Win32_Process | Where-Object {
$_.GetOwner().User -eq 'admin' -and
$_.Name -eq 'tm1top.exe'
} | ForEach-Object {
$_.Terminate()
}

Related

Windows cmd or powershell script to start an instance of a program, get its PID and stop it after a time period

I am trying to achieve the following using a command line script in windows:
Start an instance of a program (.exe) that launches a GUI (passing also some parameters to the command)
Wait a specific amount of time for the program to be executed (e.g. X second)
Terminate its execution
It can be the case that several instances of the program can run in parallel so what i am searching is a way to be able and terminate the specific instance of the program that was previously launched by the "start" command. A possible way i assume is to be able and get its PID but i am not sure if i can do that when using a simple command line script.
What i have tried is the following:
A) command line script for program's instance "A":
Start "" "C:\Program Files (x86)\XXXX\YYYY.exe" /USER=myUser /PASSWORDD=myPass /CMDLINEID=winTsk_IntSO_A
timeout 180
taskkill /F /T /IM YYYY.exe /FI "USERNAME eq domain\username"
timeout 30
exit
B) command line script for program's instance "B":
Start "" "C:\Program Files (x86)\XXXX\YYYY.exe" /USER=myUser /PASSWORDD=myPass /CMDLINEID=winTsk_IntSO_B
timeout 180
taskkill /F /T /IM YYYY.exe /FI "USERNAME eq domain\username"
timeout 30
exit
But obviously if i run the two scripts in parallel the taskkill command that is executed first, terminates both instances (i run them as windows scheduled tasks under a specific user account). The parameter that identifies uniquely each instance is the /CMDLINEID but i doubt i can filter the running tasks based on that parameter.
After #filimonic suggestion i am using the following powershell scripts to achieve the objective:
A) Powershell script for instance "A":
$process = [System.Diagnostics.Process]::Start(
'C:\Program Files (x86)\XXXX\YYYY.exe',
'/USER=myUser /PASSWORDD=myPass /CMDLINEID=winTsk_IntSO_A')
Write-Host $process.Id
Start-Sleep -Seconds 10
if (-not $process.HasExited) {
$process.Kill()
}
A) Powershell script for instance "B":
$process = [System.Diagnostics.Process]::Start(
'C:\Program Files (x86)\XXXX\YYYY.exe',
'/USER=myUser /PASSWORDD=myPass /CMDLINEID=winTsk_IntSO_B')
Write-Host $process.Id
Start-Sleep -Seconds 120
if (-not $process.HasExited) {
//Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq $ppid } | ForEach-Object { Kill-Tree $_.ProcessId }
//Stop-Process -Id $ppid
$process.Kill()
}
This is working however i have the following issue:
YYYY.exe is a GUI application that has a "loading" time ~ 60 seconds
The first script which has "10 seconds" wait period is executed normally and i can see in the task manager that the corresponding "task" is also terminated
The second script which has "120 seconds" wait period is executed normally but after its execution the "task" in task manager (same PID) remains running
Any ideas on how to more effectively terminate YYYY.exe running instance?
From one script:
$process = [System.Diagnostics.Process]::Start('cmd.exe')
$process.Id #PID here
# ... Wait something #
$process.Kill()
From second script: ($storedProcessId is somehow stored between scripts). You may requre admin permissions
$process = [System.Diagnostics.Process]::GetProcessById($storedProcessId)
$process.Kill()
Of course you may use alternaltively more powershell-native way:
$process = Start-Process -PassThrough -FileName 'cmd.exe'
Of course, there are variants with command line arguments for both ways. See docs for Process.Start and Start-Process
So your script will be like that
$process = [System.Diagnostics.Process]::Start(
'C:\Program Files (x86)\XXXX\YYYY.exe',
'/USER=myUser /PASSWORDD=myPass /CMDLINEID=winTsk_IntSO_A')
Start-Sleep -Seconds 180
if (-not $process.HasExited) {
$process.Kill()
}

Check elevated process status?

I would like to find a way to find out if a process is running as elevated or not using Powershell.
Use Case: Being able to run control panel tasks with elevated privilage as local domain user e.g. Add or Remove programs.
Any help will be appreciated.
#Start add or remove as admin
start-process appwiz.cpl -verb runas
#Check if path exists. Answer is Yes, so process is NOT elevated
get-wmiobject -class win32_process | select-object -properties name, path
These are the two usual options:
Use the #requires -RunAsAdministrator line in your script (requires PowerShell 3.0 or later). If you use this line at the top of your script, it will throw a terminating error and won't execute if the current process isn't elevated.
Use code like the following to detect whether the current process is elevated:
$IsElevated = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

Batch file or Powershell: How to Kill all Process from a particular user

I wonder how you can write a batch file or powershell script that, given an input of a user name, that it goes and kill every processes that is owned by that user.
For example, if I input user name: testuser. I want the script to go and kill every system processes that its owner is testuser.
On a Windows Server 2008, 2012.
Thanks.
use the command taskkill on windows server, you can kill any processes owned by specific user.
TASKKILL /F /FI "USERNAME eq "
Using powershell you can list all processes started by a specified user:
Get-Process -IncludeUserName | where {$_.UserName -eq "<Username here>"}
To kill/stop a process, either call .kill() on each result or feed the result into Stop-Process.

How to debug hidden powershell scripts?

I'm writing a script that normally will get called by another application (VMware vCenter Server). From that application I trigger a batch file (redirect.bat) and pass a variable which is the powershell script name (TestMe.ps1).
The script is placed on a Windows Server and when I go into the command prompt of the Windows Server and call the redirect script, I see that my PowerShell script runs as expected. However when I trigger it from the app the Powershell script is not run or doesn't produce output. I have confirmation that the redirect.bat is run, because the redirect.bat writes a line in a log file.
The vCenter Server app is running under Local System account. Could it be a permissions error? Is LocalSystem allowed to run Powershell scripts?
I now have no clue if the Powershell script even starts, because it (of course) is not visible in my console when running. The batch file always returns errorlevel = 0.
Any tips on how to insert debugging info in the script that should always give output? Tips on how to troubleshoot this?
redirect.bat:
set POWERSHELL=C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -nologo -noprofile -noninteractive
SET ERRORLEVEL =
echo %1 > G:\DataStoreAlarms\Log\Redirect-batch.txt
start %POWERSHELL% -command "&"%1""
echo Error level: %ERRORLEVEL% >> G:\DataStoreAlarms\Log\Redirect-batch.txt
I call redirect.bat from the command line and from the app like this:
redirect.bat G:\DataStoreAlarms\Scripts\TestGabrie.ps1
TestGabrie.ps1:
$String = "This is a test"
$String | Out-File -FilePath "G:\DataStoreAlarms\Log\Powershell.txt" -Append
Regards
Gabrie
Problem seemed to be the START command:
start %POWERSHELL% -command "&"%1""
After changing it to this, it worked:
%POWERSHELL% -command "&"%1""
Thanks for all your help.

Running powershell script from CMD does not load module

So i have fairly easy powershell script that contains following:
import-module activedirectory
Get-ADUser -Filter *
remove-module activedirectory
If i run it from powershell it runs OK, but when i try to call it from CMD nothing happens, it just opens powershell and thats it. I am using following command to run it:
powershell.exe -file "D:\test.ps1"
I noticed also following thing, 2 powershell.exe processes run after i execute this. If i exit from CMD from one powershell then i start seeing lists that this PS query should be returning. Is there a way to get this working since i am trying to run ps script as scheduled job. The crucial part here is import module when i run it over cmd which is not happening for some reason.
It's powershell 2.0 running on Windows 2008R2. I tried this script on win 2012r2, works fine from CMD... Looks like ps 2.0 limitation?
Could be a couple of things going on here. Since your windows opens and closes you wont get to see any errors that might be occurring. What is your ExecutionPolicy set to? Get-ExecutionPolicy
When I make scheduled tasks of my scripts I usually set up my action as such
Program/Script = %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
Arguments = -ExecutionPolicy Unrestricted -NoProfile -File C:\data\script.ps1
Start In = %SystemRoot%\system32\WindowsPowerShell\v1.0
Also, I don't believe it matters in this case but be sure you have the script "Running with highest privilege" if required.

Resources