PowerShell 3.0 - Setting Affinity to CPU per USER's PROCESS - powershell

my first post here. I am working on a script using powerShell, the objective is to set a certain amount of CPU-threads per USER's process, using the forum here, i was able to find most of the answers, and even got my script to run, except, if it sets the affinity, it sets it to EVERY-Process, not just the user i need.
here is the code(with comments):
# GET LIST of all process running
$pList = get-wmiobject win32_process
# loop through created array and get the OWNER of the processes
foreach ($p in $pList) {
#If "myUserName" is found:
if ($p.getowner().User -eq 'myUserName') {
# get process name
$procName = $p.ProcessName
# trim STRING to remove EXE
$procName = $procName.Replace('.exe','')
# use get-process to make array of processes run by "myUserName"
$activeProc = Get-Process -name $procName
# Loop to set affinity for each process
foreach ($i in $activeProc){
$i.ProcessorAffinity=0xFE
}
}
}
when i execute this command, all of the process are set to new Thread Count,
any suggestions how to make it ONLY adjust threads for SPECIFIC user?
Thanks a lot guys!
this is pretty urgent.

By calling get-process -name $procName you are finding all processes that have the same name as one run by the user.
Instead of using the ProcessName, use ProcessId.

In PowerShell version 4.0, you can use the -IncludeUserName parameter on the Get-Process cmdlet. Once you have a list of processes, you can then filter then using the Where-Object cmdlet, which has a default alias of ?.
Get-Process -IncludeUserName | Where-Object -FilterScript { $PSItem.UserName -match 'system' };
Or short-hand might look like this:
gps -inc | ? { $_.UserName -match 'system' };
Note: Using the -IncludeUserName parameter requires privilege elevation.

Related

Pipe sc query output to powershell method?

I'd like to pipe output from sc query to a method in powershell. For example, checking the status of a service and finding the part that says "STOPPED", and performing an action based on that output.
Is there a way to do this right from the output of sc query? Or do I need to output the results to a text file, and then.. I'm not sure, run a for-loop to find the piece I'm looking for to make an if condition true / false.
This is what I have so far:
Function IsStopped {
sc.exe query remoteregistry >> RemoteRegistry.txt
Get-Content -Path C:\RemoteRegistry.txt | Where-Object {$_ -like '*stopped*'} | ForEach-Object {
}
Not sure where to go next?
PowerShell has a cmdlet for examining services. Running Get-Service without parameters gives you all of the running services in the same way sc.exe does (actually while researching this I reminded myself that in PowerShell sc, without .exe, is an alias for Set-Content, so I ended up generating some useless files. This might be another good reason to use Get-Service to avoid confusion with Set-Content).
Running Get-Service | Get-Member gives a list of the properties and methods from the output of the command. Status is the Property of interest, so we run:
Get-Service | Where-Object { $_.Status -eq 'Stopped' }
The output of this command can then be piped into a for each loop as you have suggested, and each service's properties or methods can be accessed using the $_ shorthand:
Get-Service | Where-Object { $_.Status -eq 'Stopped' } | ForEach-Object {
Write-Host "Do something with $($_.ServiceName)"
}
It is possible to restart services in this manner, using $_.Start(), but I would recommend writing some error handling into the process if that's your ultimate aim.'
If you need more information, such as the executable, you might want to look here:
How can I extract "Path to executable" of all services with PowerShell

Printer Migration - Powershell script

I have found some great examples on foreach loops in Powershell here but I just can't wrap my head around foreach loops for what I am doing.
I found great scripts that deal with migrating printer when migrating from one Windows print server to another however my challenge is that I am migrating from an Novell iPrint server to a Windows server.
The struggle is that the printer name or share name (or any printer property) for iPrint printer is not the hostname so I have to come up with some translation table with iPrint name and Printer hostname.
Initially, I wanted to just have column 2 of my translation table have it execute my powershell command to install a network printer which would make things easier.
I am in the process of trying to create a logon script to query printers that are installed on computer and have it do a 'foreach' loop against a CSV with iPrint names and hostnames.
csv 1
installediprintprintername1
installediprintprintername2
installediprintprintername3
printtranslationtable.csv
column 1 column 2
iprintprintername1 hostnameprinter1
iprintprintername2 hostnameprinter2
iprintprintername3 hostnameprinter3
iprintprintername4 hostnameprinter4
This is what I got so far but not able to get it to work. Any help would be appreciated!
$printers = #(Get-wmiobject win32_printer)
$path = "\\networkdrive\printtranslationtable.csv"
$printertranslation = Import-Csv -path $path
foreach ($iprintprinter in $printtranslationtable) {
foreach ($name in $csv1) {
if ($name -eq $printtranslationtable.column1) {
Write-Host $newPrinter = $printtranslationtable.column2
}
}
}
Update
So I was able to tweak the script #TheMadTechnician suggested and able to get this PS script to work in my environment. What I am trying to do is to check if new printers are installed and if they are then just exit script. This is what I have but can't get it to exit or break. I was also trying to write the new printers into text file but not necessary, I would like for it to stop executing script.
if (($printers.name -like "\winprint*") -eq $true) {
$printers.name -like "\winprint\" | out-file -FilePath "C:\windowsprinters.txt" -Append
{break} {exit}
}
When you read the file with Import-Csv, PowerShell creates an array of custom objects with property names from the header line. On the other hand Get-Content produces simple array of string values. I came up with this one liner, which goes thru the translation table and checks if the printer list contains one. This is not optimal if you have billions of printers, but keeps things clear:
printers.txt:
iprinter2
iprinter3
printertable.csv:
"Column1";"Column2"
"iprinter1";"hostname1"
"iprinter2";"hostname2"
"iprinter3";"hostname3"
"iprinter4";"hostname4"
PowerShell:
$printers = Get-Content .\printers.txt
$prtable = Import-Csv -Delimiter ";" .\printertable.csv
$prtable | ?{ $printers -contains $_.Column1 } | %{Write-Host "Install $($_.Column2)"}
Ok, so you query what printers are installed, and you have a translation table loaded from a CSV, now you just need to look at that translation table and cross reference which entries have a listing in the local computer's printer listings.
$printers = #(Get-wmiobject win32_printer)
$path = "\\networkdrive\printtranslationtable.csv"
$printertranslation = Import-Csv -path $path
$printertranslation | Where{$_.Column1 -in $printers.ShareName} | ForEach{ Add-Printer $_.Column2 }
I don't know what property of the win32_printer object aligns best for you, but I would suggest ShareName or DeviceId. Those should be something like:
ShareName: XeroxColor02
DeviceId: \\printserver\XeroxColor02

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.

PowerShell Script to query and delete print jobs older than "x" days

I started putting this PowerShell Script together, the hope would be to replace some tasks that are currently carried out manually
I'm using the
get-Date.AddDays()
function
I'm using the ISE to build the script and in testing I get output if I single out the 'starttime' property, but this seems to be a catch all because the values all come up null, ideally I'd like to use the 'timesubmitted' property, but the date seems to output in an odd that I don't think is being read correctly because my queries with 'timesubmitted' always come up empty
it comes out in this format, if you do an open query
20120416030836.778000-420
here's what I have so far.
disregard the | 'format-table' function that's just so I can see if I'm getting the desired output
#Clears Old Print Jobs on Specified server
#Sets Execution Policy for Script to run
Set-ExecutionPolicy RemoteSigned -Force
#establishes variable for cutoff date
$d = Get-Date
$old = $d.AddDays(-4)
#Queries WMI and retrieves print jobs
Get-WmiObject -class win32_printjob -namespace "root\CIMV2" | where-object {$_.timesubmitted -lt
"$old"} | ft caption,document,jobid,jobstatus,owner,timesubmitted
In PowerShell every WMI instance has a ScriptMethod that you can use to convert the dates from WMI format to .NET format:
Get-WmiObject Win32_PrintJob |
Where-Object { $_.ConvertToDateTime($_.TimeSubmitted) -lt $old } |
Foreach-Object { $_.Delete() }
Just an update in case anyone is looking in 2021.
This command/syntax worked for me in 2008 R2 (PowerShell version 2.0) (I was able to piece this together from this page, as well as others).
Finds all jobs over 30 minutes and deletes them:
Get-wmiobject win32_printjob
| Where-Object {[System.Management.ManagementDateTimeConverter]::ToDateTime($_.TimeSubmitted) -lt (Get-Date).addminutes(-30)}
| ForEach-Object { $_.delete() }*

PowerShell get running explorer process and their documents

How can i access document property of already running explorer processes. i am using following line of code to get process.
$ie2 = Get-Process |where {$.mainWindowTItle -eq "Windowtitletext"} | where {$.ID -ne $ieParentProcessNumber}
now i want to do some processing on this processes like $ie2.Document etc.
It seems like you are trying to access the Document (i.e a webpage's data) directly from the process. This is not possible using the get-process.
You would need to create a instance of a IE com object for example or use the System.Net.WebClient if you want to just read data from a web site. Post more info about what you are trying to do and we can possibly help you out better
You can attach to the ie window:
$app = New-Object -ComObject shell.application
$popup = $app.Windows() | where {$_.LocationName -like "*foo*"}
$popup.document
If you know that you'll receive 1 object:
(Get-Process explorer).CPU
If you want to know what are the available properties:
Get-Process explorer | Get-Member
If you have more than one object in your result set (e.g. Get-Process returning mutiple processes mathing search criteria):
Get-Process | Where-Object { $_.Handles -ge 200 } | Foreach-Object { $_.CPU }