Get LogonAs account value from a Service using powershell - powershell

I have a service running with a service account. I have a logged into the machine using administrator account. I want to find username using which the service is running.
I tried below
"Get-WmiObject Win32_Process -Filter "name='myservicename*'" |
Select Name, #{Name="UserName";Expression={$_.GetOwner().Domain+"\"+$_.GetOwner().User}} |
Sort-Object UserName, Name"

As per Bill_Stewart mentioned in the comment, it worked for me
Get-WmiObject Win32_Service -Filter "Name LIKE 'myservicename%'" | Select-Object Name,StartName

Related

Powershell - Get a List of all Computers with their IP Address and Last Logged On User

i would like to get in Powershell a list of all computers (in my domain) with their IP Address and the last logged on user, the output should be something like this:
ComputerName | IpAddress | LastLoggedOnUser
ABC-123 1.2.3.4 Username
DEF-456 5.6.7.8 Username1
GHI-789 9.0.1.2 Username2
I have tried a lot of scripts but none of these worked so far :(
Thank you in advance!
Edit:
i tried this:
$computers = Get-ADComputer -Filter * | select Name
foreach($computer in $computers)
{
Get-WmiObject -ComputerName "$computer" -Class Win32_ComputerSystem | Select-Object UserName
}
but i get the error "The RPC Server is unavailable"
if i run the command
Get-WmiObject -ComputerName "[Computer Name]" -Class Win32_ComputerSystem | Select-Object UserName
it works, but shows me only one Computer.
You can append the scripts you have found to include the lastLoggedOnUser with the following command, but you would need acccess to the computer to retrieve this information.
Get-WinEvent -Computer (computer name) -FilterHashtable #{Logname='Security';ID=4672} -MaxEvents 1 | select #{N='User';E={$_.Properties[1].Value}}

filter Get-Service by username

I'm trying to get all the services that run under the user system, but just them (not from other users). I don't find a way to filter the result by the user name.
I tried many options, include Get-WmiObject.
Is there a command or a parameter like -IncludeUserName (Works with Get-Process) that makes it possible?
Thank you
Property called StartName is the username
below will filter out StartName = LocalSystem
Get-WmiObject -Class Win32_Service | Where-Object {$_.StartName -eq 'LocalSystem'}

Finding current logged on user(s) while running as SYSTEM (no environment variables)

I have created a PowerShell script that saves the current user to a report. When creating this report, it was working fine because I was using $env:USERNAME. However, now that the report is running under the SYSTEM account as a scheduled task, it saves the current user as "HOSTNAME$." Is there another easy way of getting the logged on users? The following doesn't work as well:
Get-WMIObject -class Win32_ComputerSystem | select username
Any ideas would be greatly appreciated as I need the current logged on user saved. I also need to run the report as NT AUTHORITY\SYSTEM to run the elevated tasks.
"Current user" is an ambiguous term that depends on what you're looking at. A user logged in on the desktop (locally or remotely)? A user running a background process? A user accessing an SMB share? WMI? WinRS?
Assuming that you want to identify which user is logged in on the desktop, you could check the owner of the explorer.exe process as described in this answer on ServerFault:
Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" |
ForEach-Object { $_.GetOwner() } |
Select-Object -Unique -Expand User
I was able to gather the current logged on user by using tasklist in PowerShell:
$User = tasklist /v /FI "IMAGENAME eq explorer.exe" /FO list | find "User Name:"
$User = $User.Substring(14)
Works perfectly even when ran as SYSTEM.
I know this is old, it took me all morning to get this straightened out, this gets you the current logged on user and their my docs path, since environment variables don't work under the system account.
New-PSDrive HKU Registry HKEY_USERS
$user = get-wmiobject -Class Win32_Computersystem | select Username;
$sid = (New-Object System.Security.Principal.NTAccount($user.UserName)).Translate([System.Security.Principal.SecurityIdentifier]).value
$val = (Get-Item "HKU:\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
$myDocPath = $val.GetValue("Personal");
To test using a powershell account that runs as system, follow these instructions
http://powershell-guru.com/powershell-tip-53-run-powershell-as-system/
Assuming from your original script that you are looking to return just usernames, you could use this:
Get-Process -IncludeUserName | Select-Object UserName -Unique |
Where-Object {$.UserName -notlike 'NT AUTHORITY\SYSTEM' -and
$.UserName -notlike 'NT AUTHORITY\NETWORK SERVICE' -and $_.UserName
-notlike 'NT AUTHORITY\LOCAL SERVICE'} | Format-Table -Wrap -AutoSize
I liked the Get-Process answer from #MNiles, but made it a little simpler with the filtering for explorer from the other answers
Get-Process -IncludeUserName -Name explorer | Select-Object UserName -Unique

get all ADcontroller of another domain

I'm stuck in a stupid problem that I can't figure out how to solve.
I need to get all domain controllers of a trusted domain.
With this piece of code I get all DC in the current domain Get-ADDomainController -Filter *
With this I get one DC from target domain Get-ADDomainController -domain MyTrustedDomain -Discover
But how can I get all DC in target domain?
Can't test this due to lack of AD, but you could try the -Server option with the FQDN of the trusted domain:
Get-ADDomainController -Filter * -Server trusted.example.com
One way without using AD module:
$a = new-object 'System.DirectoryServices.ActiveDirectory.DirectoryContext'("domain", "other.domain.local" )
[System.DirectoryServices.ActiveDirectory.DomainController]::FindAll($a)
You need to be an 'authenticated user' in the remote domain or add username and password parameter to the DirectoryContext object
This command will list all domain controllers in the forest for each domain
(get-adforest).domains |%{get-addomaincontrollers -filter * -server $_}
I've come across the same problem as I work regularly with multiple domains. I was hoping for a more elegant solution, but so far the best I've come up with is to take your work one step further.
if Get-ADDomainController -domain MyTrustedDomain -Discover gives you one server in the target domain, you can feed that to the -server parameter to query that one DC. You do need to provide credentials to query a DC from a different domain than your login session if a trust DOES NOT exist (in a trust, the trusting domain considers you to be 'authenticated').
$targetdcname = (Get-ADDomainController -DomainName <MyTrustedDomain> -Discover).hostname
Get-ADDomainController -Filter * `
-Server $targetdcname `
-Credential (Get-Credential MyTrustedDomain\username) | ft HostName
or
Get-ADDomainController -Filter * `
-Server $((Get-ADDomainController -DomainName <MyTrustedDomain> -Discover).hostname) `
-Credential (Get-Credential MyTrustedDomain\username) | ft HostName
If you do this sort of thing alot, you can always store your credentials in a variable for reuse, $cred = Get-Credential MyTrustedDomain\username) and save the repeated prompts. The password is stored as a System.Security.SecureString and will be secure as long as you keep it within your session.
Until the Get-ADDomainController cmdlet is updated to allow both the -filter parameter AND the Domainname parameter, we're stuck with a workaround.
from: help get-addomaincontroller -examples
This should list all DCs in your domain
-------------------------- EXAMPLE 12 --------------------------
C:\PS>Get-ADDomainController -Filter { isGlobalCatalog -eq $true -and Site -eq "Default-First-Site-Name" }
Get all global catalogs in a given site.
Get-ADDomain -Identity <DOMAIN NAME> | select -ExpandProperty ReplicaDirectoryServers
Here is what I used
cls
$domains = (Get-ADForest).Domains;
foreach ($domain in $domains)
{
Write-Host $domain
(Get-ADDomain -Identity $domain | select -ExpandProperty ReplicaDirectoryServers).Count;
Write-Host "";
$totalCount = $totalCount + (Get-ADDomain -Identity $domain | select -ExpandProperty ReplicaDirectoryServers).Count;
}
Write-Host "Total domain controller count is: "$totalCount
Thanks for the start, here's what I came up with. Then I feed it to a SharePoint list.
get-adtrust -Filter * | Select-object Name, Domain,ipv4Address, OperatingSystem, Site, HostName, OperatingSystemVersion | ForEach-Object{Get-ADDomainController -Filter * -Server $_.Name}
Sometimes Powershell adds complexity, just open a cmd prompt and enter
C:\Windows\System32\nltest.exe /dclist:[trusted domain]
Of course, replace [trusted domain] with the name of the domain whose DC's you want.

Delete local windows profile with PowerShell

I am trying to write a script that will delete the local profile of a test account. I am using the following line to return the SID of any account that starts with "test-"
PowerShell: $UserSID = (Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -like '*\test-*'}).SID
Once I had the SID I used wmic to do the deletion but, I am not sure how to translate that code into PowerShell.
WMIC:wmic /node:"localhost" path win32_UserProfile where Sid="%%b" Delete
I was thinking this would work, but I don't find a delete method on the Win32_UserProfile class
$UserSID = (Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -like '*\test-*'}).SID
(gwmi -class Win32_UserProfile -filter "SID='$UserSID'").Delete()
You can also just call the Delete method directly in a single statement:
(Get-WmiObject Win32_UserProfile | Where {$_.LocalPath -like '*\test-*'}).Delete()
Another reason of getting Exception calling "Delete" with "0" argument(s) is the user you're trying to delete is currently logged in. Log him off and try again.
Get-WmiObject Win32_UserProfile -Filter "RoamingConfigured = 'True'" | Remove-WmiObject
True - Roaming profile
False - Local Profile
I resolved this issue by opening Powershell as administrator (right click, Run as Administrator).