List and kill multiple processes in PowerShell having same username - windows

I have 4-5 process (like java.exe, javaw.exe etc) having username "OWNER"(suppose). Below is the script that filters the java.exe process and kills it if it belongs to "OWNER". I need your help to modify this so that any process related to "OWNER" would be killed if found.

Just do it with Get-Process:
get-process -IncludeUserName | where username -like $username | stop-process
Basically your whole script can be replaced with this line

Get-Process with -IncludeUsername switch is only available in WMF 5.0.
WMI is the option here.
You could probably terminate the process just by checking the owner equals to the corresponding user.
Get-WmiObject -Class Win32_Process | Where-Object -FilterScript {
$_.GetOwner.User -eq "$Owner" } | Invoke-WmiMethod -Name Terminate
Edit: The above code is a one liner, you could save the out put of Get-WmiObject in a variable and for foreach through the collection to print the process id and call the terminate() method instead of using Invoke-WmiMethod.
Note:This code is not tested

Related

fsmgmt.msc | stop process are running from specific directory | Remote server with invoke

I want to stop all the processes are running from specific directory if the process is from C:/CSV/X kill the process the server is remote but I have users are opened the files from different sessions so how can I kill it from different sessions
$files = gci "C:\CSV\X\*"
foreach($file in $files){
Get-Process |
Where-Object {$_.Path -eq $file.FullName} |
Stop-Process -Force -Verbose
}
I tried it and it doesn't work
For example we have a folder named: MyItem Inside the folder there is
MyItem/software.exe
MyItem/MyItem.exe
MyItem/MainMenu.exe
And I look for the processes through this: fsmgmt.msc
So I need to find a way to close all those whose source is MyItem/
If you only want to terminate 'open files' accessed from the network you can do something like this:
#set path
$path = 'C:\CSV\X\'
#get smb open files in specified directory and close em, escape $path \ because of -match operator (regex)
Get-SmbOpenFile | ?{$_.path -match ($path -replace '\\','\\')} | Close-SmbOpenFile
No need to kill processes.

running remotely ps commands

i have written a script which acts like a gpo editor, it can get some GPO and OU and link them or unlink them depending on user's wish. now this script does work when its running on Domain Controller machine but i need it to run on a windows 10 machine workstation on the domain. so i need to do the adjusment while showing the user the GUI, all the code must invoke the commands on the dc. i dont know whats the problem but when i enter the commands manually one by one it works and when its running as a script i get errors:
for example here is a function for a link button . (i have a gui with 2 listboxes. one showing the GPO's and one showing the OU (the ou is shown as CanonicalName and not as Distinguishedname hence the $SWITCH variable to go back and forth so the user will see it in a more friendly way)
function LinkFn {
$ResultsTextBox.clear()
#This $SWITCH is used to Translate the user selection from the OU listbox from canonical back to distinguishedname
$SWITCH = Get-ADOrganizationalUnit -filter * -Property CanonicalName | Where-Object {$_.CanonicalName -eq $listBox2.SelectedItem}
ForEach ($line in $listBox1.selecteditems){
try {
Invoke-Command -ComputerName "$DCNAME" -ScriptBlock {New-GPlink -name $line -target $SWITCH -ErrorAction STOP | Out-null}
$ResultsTextBox.AppendText("`n GPO: $line HAVE BEEN LINKED Successfully.`n")
}
catch{
$ResultsTextBox.AppendText("`n$line ALREADY LINKED! TO THIS OU `n")
}}}
can someone help?
From what i see, i think there is a problem with the code line:
$SWITCH = Invoke-Command -ComputerName "$DCNAME" -ScriptBlock {Get-ADOrganizationalUnit -filter * -Property CanonicalName | Where-Object {$_.CanonicalName -eq $listBox2.SelectedItem}}
$switch is coming up empty (where it runs fine on dc), any idea why?
write your try catch block like below. You have to use $using:variable to use the variables declared outside of the scriptblock.;
try {
Invoke-Command -ComputerName "$DCNAME" -ScriptBlock {New-GPlink -name $using:line -target $using:SWITCH -ErrorAction STOP | Out-null}
$ResultsTextBox.AppendText("`n GPO: $line HAVE BEEN LINKED Successfully.`n")
}
catch{
$ResultsTextBox.AppendText("`n$line ALREADY LINKED! TO THIS OU `n")
}
Also, if the user does not have access to connect / remote to the DC, this wont work. User running the script will need admin level access to the DCs or use credentials for account that actually have access.

status of the process in powershell

A process in windows can be in any of the six states i.e, running, ready, blocked, suspend, new and exit. How to know the state a given process (name, ID) using powershell in windows.
In UNIX this information is stored in /proc/$processid/status file. Where is it found in windows or how to get this information in powershell.
"exit" status is signified by the presense of "exit code" property (natively returned by GetExitCodeProcess()). In PS, it is reflected by HasExited and ExitCode fields in Get-Process (alias ps).
ps | where {$_.Id -eq <PID>} | select HasExited,ExitCode
"running/wait/suspended" in Windows is a status of a thread rather than process ("suspend" being one of several Wait substates). I didn't find any info on getting thread information by PS's built-in means but we can call the corresponding .NET functionality:
$process=[System.Diagnostics.Process]::GetProcessById(<PID>)
$threads=$process.Threads
$threads | select Id,ThreadState,WaitReason
You are right, that's an interesting point. A way to find out about the state the process is the following way :
$ProcessActive = Get-Process outlook -ErrorAction SilentlyContinue
if($ProcessActive -eq $null)
{
Write-host "I am not running"
}
else
{
Write-host "I am running"
}
If outlook would not be a running process, it would not be listed but -ErrorAction SilentlyContinue will simply continue and return an I am not running
If it's running it will send you an I am running
I am not aware of other states of a process... at least not how to dertermine

How to pull physical path of a Windows Service using Get-Service command

I need to pull Physical Execution paths of all the Windows Services on a Set of Servers, that run on Win 2k8. As, the powershell version that is shipped with this OS is 2.0, I wanted to use Get-service command instead of Get-WmiObject.
I know that I can pull the physical path using the command given below
$QueryApp = "Select * from Win32_Service Where Name='AxInstSV'"
$Path = (Get-WmiObject -ComputerName MyServer -Query $QueryApp).PathName
I donot want this command to pull the physical path but wanted to use Get-Service command that comes with PS Version 2.0.
Any help would be much appreciated.
Even with PowerShell 3, I don't see a way to get it with Get-Service.
This 1-liner will get you the pathname, albeit with a little less of the preferred "filter left" behavior:
gwmi win32_service|?{$_.name -eq "AxInstSV"}|select pathname
Or, if you want just the string itself:
(gwmi win32_service|?{$_.name -eq "AxInstSV"}).pathname
#alroc did good, but there's no reason to filter all services. Querying WMI is like querying a DB, and you can just ask WMI to do the filtering for you:
(Get-CimInstance Win32_Service -Filter 'Name = "AxInstSV"').PathName
To explore all of the meta available for that service:
Get-CimInstance Win32_Service -Filter 'Name = "AxInstSV"' | Select-Object *
I wanted to do something similar, but based on searching / matching the path of the process running under the service, so I used the classic WMI Query syntax, then passed the results through format-table:
$pathWildSearch = "orton";
gwmi -Query "select * from win32_service where pathname like '%$pathWildSearch%' and state='Running'" | Format-Table -Property Name, State, PathName -AutoSize -Wrap
You're welcome to turn this into a one-liner by skipping defining and passing $pathWildSearch, or you could just back gwmi statement up to continue after the semi-colon.
Perhaps little less verbose,
wmic service where "name='AxInstSV'" get PathName
This should work on command prompt as well, not just powershell.
Or else if you have process name itself you could do:
wmic process where "name='AxInstSV.exe'" get ExecutablePath
To read process path you would need permission, so mostly I have better luck with service name.
I was never able to do this through the Get-Service command but if your service runs as it's own process then you can use the Get-Process command for this via the following code:
(Get-Process -Name AxInstSV).path
Source:
https://blogs.technet.microsoft.com/heyscriptingguy/2014/09/15/powertip-use-powershell-to-find-path-for-processes/

PowerShell: Restart Service By Executable Name

all
I implemented my first PowerShell script, that does some setup, sets registry keys and at then end needs to restart services. The problem is that I have only have name of the executable, but not service name. Restart-Service can work only with name of the service. Googling (well Binging also) around didn't give me much result.
I was wondering whether there is a way to restart service by executable name?
I know that I can get process by executable name, but just killing the process and starting it again is NOT good choice, since service Start/Stop functions are not called and it may not work properly.
Thanks.
You can try using wmi and do something like this:
(gwmi win32_service | ?{$_.pathname -match "\\executable.exe "}) | Restart-Service
Get-WmiObject -Class Win32_Service -Filter "PathName LIKE '%PartOfTheName%'" -ComputerName PC1 | Foreach-Object{
$_.StopService()
$_.StartService()
}
You can do this using WMI:
$process = Get-Process sqlservr| select -ExpandProperty Id
Get-WmiObject win32_Service|
where {$process -contains $_.ProcessId}|
foreach {Restart-Service $_.Name}
Edit: Changed script to restart service, not just stop it.
#set by logic to determine if the service will restart or not
$global:ServerWillRestart=$true
#can be found using the name column of Get-services cmdlet
$serviceName="Set name of the service"
if($global:ServerWillRestart){
$service =Get-Service | where{ $_.Name -eq $serviceName}
do{
Write-output "The service $ServiceName will is being stopped"
Stop-Service $service
Start-Sleep -s 2
}
while($service.WaitForStatus("Stopped"))
do{
Write-Output "The service $ServiceName will is being started"
Start-Service $service
Start-Sleep -s 2
}
while($service.WaitForStatus("Running"))

Resources