Get username for PID (ProcessId) - powershell

I have a PID for which I want to check its username. I knew that we can use GetOwner(), but it is the valid method for Get-WmiObject Win32_Process. I am using Get-WmiObject -Class Win32_PerfRawData_PerfProc_Process in which there is no way to get username (as per I search online). So, I think to check PID separately is the only way to resolve this.
Can you please tell me how can I get the username of PID or get username inside Win32_PerfRawData_PerfProc_Process?

As it is described in this technet article :Technet you can use the code below.
In the last line you can put the process you want after the get-process command.
e.g. Get-Process outlook | select processname,Id,#{l="Owner";e={$owners[$_.id.tostring()]}}
$owners = #{}
gwmi win32_process |% {$owners[$_.handle] = $_.getowner().user}
Get-Process | select processname,Id,#{l="Owner";e={$owners[$_.id.tostring()]}}
The time it takes depends on how many services are currently running.
Your output will be like:
ProcessName Id Owner
----------- -- -----
OUTLOOK 13128 UserName
Hope that helps.
Kind regards.

Related

Fetching values from Net Use command using powershell

I am trying to get network mapped drives using below commands.
Get-WmiObject -Class Win32_MappedLogicalDisk | %{$_.Name}
Get-WmiObject -Class Win32_MappedLogicalDisk | %{$_.ProviderName}
This works in some system however does not in other systems(may be powershell version issue) So I thought of using net use command. However, I am unable to fetch the values or not sure how to get the values displays when i type 'net use'
when I type net use I get status, Local, Remote and Network column. I tried to use the below command to get the field values.
net use | select local.
but I get blank or nothing
Used below command.
net use | select local.
Need to get Local and Remote values from net use command.
See this for parsing legacy console output ---
How to Convert Text Output of a Legacy Console Application to PowerShell Objects
Yet, along with what LotPings gave you already. Your query could be a duplicate of this ...
Equivalent of net use (to list computer's connections) in powershell?
... and it's accepted answer
# For the mapped logical drive you can use WMI class Win32_MappedLogicalDisk :
Get-WmiObject Win32_MappedLogicalDisk
# Here is another way with Win32_LogicalDisk :
PS C:\> Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = 4"
DeviceID : V:
DriveType : 4
ProviderName : \\jpbdellf1\c$
FreeSpace :
Size :
VolumeName :
# Edited
# You are right, you can get what you need with Win32_NetworkConnection :
Get-WmiObject Win32_NetworkConnection
LocalName RemoteName ConnectionState Status
--------- ---------- --------------- ------
\\jpbasusf1\temp Connected OK
# On Seven or W2K8 be careful to call this with the same user that run the NET USE because it's a session information.
How about using get-psdrive (the root header actually matches the displayroot property)?
get-psdrive | where displayroot -like '\\*'
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
Y 91.84 7.82 FileSystem \\server....
Depending on the PowerShell versions available you might encounter similar problems with
Get-SmbMapping which wraps the CimClass: ROOT/Microsoft/Windows/SMB:MSFT_SmbMapping.
But has otherwise an output resembling net use.
To process the real net use output and convert to an object with properties,
you may use:
$SmbMapping = (net use) -like '* \\*' | ForEach-Object {
$Status,$Local,$Remote,$Null = $_ -split ' +',4
[PSCustomObject]#{
Status = $Status
Local = $Local
Remote = $Remote
}
}
This works at least in my German locale Win10.
(Not sure about different status messages in other locales.)

PowerShell to Get local user membership remotely

Need some help here.
I need to get the local user list of a remote computer and what group they belong to using PowerShell script.
I tried:
Get-LocalUser
Get-LocalGroup
Get-LocalGroupMember
Also:
gwmi win32_UserAccount
gwmi win32_group
but it is very slow and pulling the information more than requirement which consumes time.
I would like the output formatted something like below:
User Memberof
------ --------------------
abc12 Administrators
efg23 remote desktop users
hij45 Administrators,Backup Operators,users
xyz56 remote desktop users,Backup Operators
Thanks in Advance,
Cheers.
I use ADSI and it's pretty quick.
$RemoteComputerName = 'RemoteComputer'
$LocalGroup = 'Remote Desktop Users'
$ADSI = [ADSI]("WinNT://$RemoteComputerName,Computer")
$Group = $ADSI.PSBase.Children.Find($LocalGroup,'Group')
$Group.PSBase.Invoke('Members').Foreach{ $_.GetType().InvokeMember('Name','GetProperty',$null,$_,$null) }

Is there a way to get a hostname from an IP address without depending on a DNS inquiry?

I'm trying to write a script that depends on knowing the names of the computers on a network segment, but all the scripts I've found depend on a DNS inquiry which only replys with the names of a few of the machines. For example:
[System.Net.Dns]::GetHostbyAddress($IPAddress)
I've also tried using
Ping -a $ipaddress
but this often fails to return the machine name as well. Is there a way to ask the host what it's name is directly and what level of permissions might be required in AD to get a response?
Thanks in advance.
[System.Net.DNS]::GetHostByAddress() (now [System.Net.DNS]::GetHostEntry()) doesn't only rely on DNS, despite it's name. It will also check the local C:\Windows\System32\Drivers\etc\hosts file for locally configured entries.
straight dns via nslookup can't find the name:
PS C:\Users\Tim> nslookup 192.168.1.50
Server: dns03
Address: 192.168.2.103
*** rpi03 can't find 192.168.1.50: Non-existent domain
yet, gethostentry() still finds the name:
PS C:\Users\Tim> [system.net.dns]::gethostentry('192.168.1.50')
HostName Aliases AddressList
-------- ------- -----------
localentry {} {192.168.1.50}
COMMAND:
wmic.exe /node:10.20.30.40 OS get CSName /format:list
BATCH FILE FOR WHOLE SUBNET:
for /L %%z in (1,1,254) do wmic.exe /node:10.20.30.%%z OS get CSName /format:list 2>NUL
You can try by using something like:
Invoke-Command -computername $computer {Get-Item HKLM:\SYSTEM\ControlSet001\Control\ComputerName\ActiveComputerName}
The active computername is equal to your DNS name (without suffix ofcourse)
I may misunderstand the problem but you can query the Win32_ComputerSystem instance using a CIM session to the remote computer and use one of those properties (Name, DNSName, etc.) Running locally it would be like
Get-CimInstance -namespace root/cimv2 -classname Win32_ComputerSystem | fl *
I'm aware that WMI might take fairly hefty permissions (e.g., domain admin) but (a) that might not be out of the question for your use case and (b) you might be able to do some limited querying with fewer permissions.
Another idea might be to query your SCCM server if you have one:
(Get-WmiObject -Query "SELECT * from SMS_R_SYSTEM WHERE IPAddresses LIKE '%$ipaddress%'" -Namespace "root\sms\site_$SiteCode" -computerName $SCCMServer).Name
Another idea using powershell:
Get-WmiObject -Class Win32_ComputerSystem -ComputerName $Computer -Property Name | ForEach-Object {$_.Name}
Where $Computer is an IP address

Need Script to find server activation status

We have an environment with different domains and forests with and without trusts.
I need to manage the license for these with out KMS.
I want to find out the servers which are running without activated or with Grace period.
I have been trying with differnt scripts from WMIC and Powershell. But, not able to generate with clear and clean.
Below are the scripts tried. I need assistance on this.
From WMIC:
WMIC /Output:#D:\output.txt /node:#D:\serverslist.txt PATH SoftwareLicensingProduct WHERE "ProductKeyID like '%-%' AND Description like '%Windows%'" get LicenseStatus
From Powershell:
PS C:\Windows\system32> Get-CimInstance -ClassName SoftwareLicensingProduct |where PartialProductKey |select PScomputername,LicenseStatus
I need help to generate a table with computer name/IP and license status.
Thanks in advance.
Here you go, I just made a few tweaks.
For one, your code returns the LicenseStatus as a number...which is OK, but to get some real wow-factor, I consulted this chart from MSDN on what the numbers mean, and used that with a Switch Statement, within a Calulated Property to replace the number with the human-meaningful license status, giving us logic like this:
select Pscomputername,Name,#{Name='LicenseStatus';Exp={
switch ($_.LicenseStatus)
{
0 {'Unlicensed'}
1 {'licensed'}
2 {'OOBGrace'}
3 {'OOTGrace'}
4 {'NonGenuineGrace'}
5 {'Notification'}
6 {'ExtendedGrace'}
Default {'Undetected'}
}
#EndofCalulatedProperty
}}
This gives us full code, like this, and also extracts the name of the product as well. You can run this against multiple systems by just adding their names to the -ComputerName property:
Get-CimInstance -ClassName SoftwareLicensingProduct -computerName localhost,dc01,windows10 |
where PartialProductKey | select Pscomputername,Name,#{Name='LicenseStatus';Exp={
switch ($_.LicenseStatus)
{
0 {'Unlicensed'}
1 {'licensed'}
2 {'OOBGrace'}
3 {'OOTGrace'}
4 {'NonGenuineGrace'}
5 {'Notification'}
6 {'ExtendedGrace'}
Default {'Undetected'}
}
#EndOfCaltulatedProperty
}}
This gives you results like this:
PSComputerName Name LicenseStatus
-------------- ---- -------------
localhost Office 15, OfficeProPlusVL_MAK edition licensed
localhost Windows(R), ServerDatacenter edition licensed
dc01 Windows(R), ServerStandard edition licensed
Windows10 Windows(R), ServerStandard edition licensed
you may also try
$activation = (Get-CimInstance -ClassName SoftwareLicensingProduct | where ApplicationId -EQ 55c92734-d682-4d71-983e-d6ec3f16059f | where PartialProductKey).LicenseStatus
Get-CimInstance -ClassName SoftwareLicensingProduct |
where PartialProductKey |
select Name, ApplicationId, LicenseStatus

How do I find the properties available from a powershell command?

I want to find what the possible columns or elements are from the get-service command. I am mostly interested in finding the log on as value a service runs under, but it'd be nice to know how to find others when the need arises.
Use the Get-Member cmdlet - gm in short
Get-Service | gm
Coming to Log On As, I think Get-Service ( or rather the [ServiceController] type)
does not expose it. You can use WMI though:
gwmi win32_service | select name, startname