Showing currently logged in user in a PowerShell running from a RMM Software as SYSTEM - powershell

i searched hours of my time and saw many ideas for this scenario but nothing worked for my like it should (i tested every code i saw on my own machine but nothing got me to the result i wanted.)
background: we are using a script in our RMM Software to Rename the Agents
$benutzer = [Environment]::UserName
Set-ItemProperty -Path "HKLM:\Software\MMSOFT Design\PC Monitor" -Name ComputerName -Value "$env:USERDOMAIN - $env:Computername - $benutzer"
This script gives us for the $env:USERNAME the user SYSTEM but we actually want the real USERNAME which is logged into this system.
Please help me out :)

The environment variable [System.Environment]::GetEnvironmentVariable('username') will give you the username for the executor of the script, in your case that is System because this is user who ran the code.
If you want to user the environment variable for the user, you must make it so the script been ran from or on behalf of the user, this also means that user must have "permissions" to modify the registry.
If I understand right, you need to know who is the "Logged in user" for the machine where that script runs, unfortunately there is nothing available from PowerShell that do that to my knowledge, instead you could use the build-in tool query for Windows machines, which will provide you with a list with all logged in users to that machine, you would need to further test it to get what you want from it, the output looks like this :
PS C:\Users\t-user> query user
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>t-user console 1 Active none 8/29/2022 11:58 AM
The trick with query user is that it will provide you with the list of users in case more than one have logged in.
I see what you are trying to do, and here is a "dirty" example of doing it :
$loggedUserList= query user
if($loggedUserList.count -eq 2){
$user = $loggedUserList -split ">" -replace '\s\s+', ';' | convertfrom-csv -Delimiter ';' | select -ExpandProperty username
Write-Host "Logged in user is - $user"
}else{
Write-Host "More than one user have signed"
}

Related

PowerShell - showing a message on remote computer screen

When I am running commands or installing software remotely using PowerShell - Invoke-Command etc I would like sometimes to be able to show a message on the remote screen so the user knows something is happening, or when work done etc.
I would like to if possible make this message look as professional as possible, e.g. better than just a standard winform message box if it can be done? perhaps more the style of the Windows 10 ones with coloured background and use of image if possible.
Spent a while googling but most seem to relate to using obsolete methods such as net-send or using msg.exe.
Thanks
https://michlstechblog.info/blog/powershell-show-a-messagebox/
So the issue really isnt creating the messagebox itself, its having it show on the users session.
So when you run a command against a system, youre using your creds to run the command therefore it wont show in the users session. You can get around this by running it in the users context using a task scheduler. I have a script that does all this for you but, id hate to recreate the wheel and will have to wait till monday (when im at work) to post it here.
It accepts user input in your sessions that outputs it to a vbs, which then copies it over the message to the users machine, and a task schedule is set to run immediately for the user thats logged in.
edit: The script is this without the task scheduler. I just invoke gwmi win32_computersystem | Select -ExpandProperty username to get the current user logged in and add it to the task.
#Prompt for messge
$strMSG = Read-Host -Prompt "Enter message"
#deleting vbs if it exists
del C:\brief\test.vbs
#creating vbs from scratch so it doesnt override
New-Item C:\brief\test.vbs
#Appending each the values to a seperate line
Add-Content C:\brief\test.vbs 'Set objShell = Wscript.CreateObject("WScript.Shell")'
Add-Content C:\brief\test.vbs "strText = `"$strMSG`""
Add-Content C:\brief\test.vbs 'intButton = objShell.Popup(strText,0,"Computer Support",48)'
#calling on the script
& cscript C:\brief\test.vbs
Found a great solution here which appears on quick testing to work well for displaying a toast notification on a remote machine
https://smsagent.blog/2019/06/11/just-for-fun-send-a-remote-toast-notification/

SID for Administrators group doesn't show in a member account

Now, before I start, I will let you in on a secret: this is on a Domain Controller.*
*The above statement is stricken due to irrelevance as the only significant change that occurs to the Local Administrator account and the Local Administrator Group (within the context and scope of this question) is minimal and doesn't alter the outcome enough to require differentiation.
I didn't have this kind of trouble on any of the other servers and I am willing to bet that the reason behind it is because it is on a DC.*
*Same reason as stated above. The accepted answer explains the inconsistency and was an oversight on my part, not the architecture (read features) of Windows Security or Domain Controllers.
I have been playing around with a few ideas on how to check if a script has been called from an account that is either the local Administrator or, at the very least, called by an account that is part of the Local Administrators group.
I have renamed the local Admin account, however, I know that I can see if the script has been called by local Admin account by typing:
(New-Object System.Security.Principal.NTAccount('reserved')).Translate([System.Security.Principal.SecurityIdentifier]).Value
and I can see if the SID ends in -500.
The problem occurs when I run a condition to see if the calling account is part of the Administrators group (which is a larger scope) by typing:
PS> [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).Groups -match "S-1-5-32-544")
PS> False
A quick check to see what account it was using:
PS> $env:username
PS> reserved
or the needlessly complicated way (though I prefer it sometimes):
PS> Write-Host ((Get-WmiObject Win32_Account | ?{$_.SID.Substring($_.SID.Length-4,4) -eq '-500'}).Caption).Split("\",2)[1] -fore GREEN
PS> reserved
and I even type:
PS> net user reserved
where it tells me Local Group Memberships *Administrators.
I pull up ADUC (dsa.msc) and I look in the Builtin container and double-click on the Administrators group. I select the Members tag and lo, and behold, reserved is actually a member!
So, a recap:
By typing net user reserved, I was able to verify it was part of the Local Administrators group
I looked in ADUC and verified reserved was a member of the builtin Administrators group
I ensured reserved was indeed the Local Administrator account by verifying the SID started with S-1-5... and ended with ...-500
To take it a step further, I made sure the SID matched the Active Directory Group named "Administrators" by typing Get-ADGroup -Identity "Administrators". I then typed Get-ADGroupMember -Identity "Administrators" and made sure reserved was listed (it was AND the SID matched!).
When I check to see if the well-known Administrators Group SID is found in the Groups of that account (by getting the current Windows Identity), it says that it isn't.
What gives?
Why do I get every indication that it actually is a member of the Local Administrators group but that SID isn't found in the account's groups?
When a computer is promoted to a domain controller, there are no more local users or groups on the machine. Member computers have local users and groups, and can also use domain users and groups for authentication, but on a DC, there are only domain objects.
See also: https://serverfault.com/a/264327/236470
I happened to stumble across something and I realized the answer to this question. For the sake of those that come here looking for assistance, here is the answer to my question:
Very simply--in regards to Powershell--if the Administrator Group SID (S-1-5-32-544) does not show up in the Groups of the user, that is a first-line indication that the script is not running with Administrative credentials.
For example, when I type out:
([Security.Principal.WindowsIdentity]::GetCurrent()).Groups
and I do not see the Administrator Group SID listed even though I know for a fact that the account I am signed into is a member of the Administrator Group, it means the current Powershell process does not have Administrative credentials.
If you click Run As Administrator and type the same as above, you will see that it lists the Administrator Group SID in Groups.
The reason why I was experiencing the inconsistency is simply because I was not running the Powershell process as an Administrator.
So, in short, there are a few ways you can check to verify if your current Powershell session has Administrator credentials. The first one is found in countless websites around the internet and is very common (I did not write this one):
$myWindowsID = [Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal = New-Object Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
if($myWindowsPrincipal.IsInRole($adminRole)) {
\\ TODO: Process is running as Administrator
Clear-Host
} else {
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "Powershell"
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
$newProcess.Verb = "runas"
[System.Diagnostics.Process]::Start($newProcess)
exit
}
Here is another way (I did write this one):
[Security.Principal.WindowsIdentity]::GetCurrent() | %{
if($_.Groups -contains "S-1-5-32-544") {
\\ TODO: Process is running as Administrator
Clear-Host
} else {
Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
exit
}
}
# The Foreach-Object (%) could be replaced with another pipeline filter
I see a lot of people asking this question and because of Powershell appealing to many Systems Administrator (especially ones without a background in programming), I really think this will come in handy for others down the line.

Using Read-Host to output information from a script

I am trying to run a script against exchange to bring back all of the mailboxes a certain user has access to. I want to be able to input the usersname using read-host. I currently have this:
$username = Read-Host("Please enter users username")
#Enable Exchange cmdlets
add-pssnapin *exchange* -erroraction SilentlyContinue
Get-MailBox | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
However, when I run this via powershell, it asks for the username, looks like it is starting to run the script, then powershell just exits and there is not data outputted
Any help would be greatly appreciated
Thanks for all the help
I finally figured it out and there were a couple of issues. It was to do with the result size. I added -resultsize unlimited:
$username = Read-Host("Please enter users username")
add-pssnapin *exchange* -erroraction SilentlyContinue
>Get-MailBox -resultsize unlimited | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
It would also not work by running the .ps1 file as this was not run by admin, and it needs admin permissions to output to the location I want. Once I created a shortcut for it to run via the powershell.exe with admin credentials it is now working as expected.
The problem is that you are only out putting to the screen.
This means that when you run your script it will carry out the required action, print to screen and close the window immidiatly. In turn, this means you can't see the output.
As #DarkLite1 mentioned, you could output to a file.
Or, you could simply allow the console to wait before closing. This is done like this at the end of your code:
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
You may also need a Write-Host on the last action in your code snippet, I'm not entirely sure as I am not familiar with how Get-Mailbox works, but try it without first.
To summarize, You must keep the window open or print the results to file to actually see anything. The code you have currently will complete so fast you will never see any output.

Configure SharePoint 2010 UPS with PowerShell

SOLUTION FOUND: For anyone else that happens to come across this problem, have a look-see at this: http://www.harbar.net/archive/2010/10/30/avoiding-the-default-schema-issue-when-creating-the-user-profile.aspx
TL;DR When you create UPS through CA, it creates a dbo user and schema on the SQL server using the farm account, however when doing it through powershell it creates it with a schema and user named after the farm account, but still tries to manage SQL using the dbo schema, which of course fails terribly.
NOTE: I've only included the parts of my script I believe to be relevant. I can provide other parts as needed.
I'm at my wit's end on this one. Everything seems to work fine, except the UPS Synchronization service is stuck on "Starting", and I've left it over 12 hours.
It works fine when it's set up through the GUI, but I'm trying to automate every step possible. While automating I'm trying to include every option available from the GUI so that it's present if it ever needs to be changed.
Here's what I have so far:
$domain = "DOMAIN"
$fqdn = "fully.qualified.domain.name"
$admin_pass = "password"
New-SPManagedPath "personal" -WebApplication "http://portal.$($fqdn):9000/"
$upsPool = New-SPServiceApplicationPool -Name "SharePoint - UPS" -Account "$domain\spsvc"
$upsApp = New-SPProfileServiceApplication -Name "UPS" -ApplicationPool $upsPool -MySiteLocation "http://portal.$($fqdn):9000/" -MySiteManagedPath "personal" -ProfileDBName "UPS_ProfileDB" -ProfileSyncDBName "UPS_SyncDB" -SocialDBName "UPS_SocialDB" -SiteNamingConflictResolution "None"
New-SPProfileServiceApplicationProxy -ServiceApplication $upsApp -Name "UPS Proxy" -DefaultProxyGroup
$upsServ = Get-SPServiceInstance | Where-Object {$_.TypeName -eq "User Profile Service"}
Start-SPServiceInstance $upsServ.Id
$upsSync = Get-SPServiceInstance | Where-Object {$_.TypeName -eq "User Profile Synchronization Service"}
$upsApp.SetSynchronizationMachine("Portal", $upsSync.Id, "$domain\spfarm", $admin_pass)
$upsApp.Update()
Start-SPServiceInstance $upsSync.Id
I've tried running each line one at a time by just copying it directly into the shell window after defining the variables, and none of them give an error, but there has to be something the CA GUI does that I'm missing.
For anyone else that happens to come across this problem, have a look-see at this: http://www.harbar.net/archive/2010/10/30/avoiding-the-default-schema-issue-when-creating-the-user-profile.aspx
TL;DR When you create UPS through CA, it creates a dbo user and schema on the SQL server using the farm account, however when doing it through powershell it creates it with a schema and user named after the farm account, but still tries to manage SQL using the dbo schema, which of course fails terribly.
The workaround is to put my code into its own script file, and then use Start-Process to run the script as the farm account (it's a lot cleaner than the Job method described in the linked article):
$credential = Get-Credential ("$domain\spfarm", $SecureString)
Start-Process -FilePath powershell.exe -ArgumentList "-File C:\upsSync.ps1" -Credential $credential

Powershell - last logged on user - same input, different output

UPDATE
# HAL9256
Your answer really made me think!
I did some more googling, and found this website which offers another approach
http://blogs.technet.com/b/heyscriptingguy/archive/2012/02/19/use-powershell-to-find-last-logon-times-for-virtual-workstations.aspx
So far, it works!
I remote into another server to run a powershell script that displays the last logged on user.
Several things
It only works when I run it in the context of a service account, not
the Administrator
It takes several minutes to output
But when I run it in the contenxt of a service account, I get different output for the same input
$line_array = #()
$multi_array = #()
[hashtable]$my_hash = #{}
foreach ($i in $args){
$line_array+= $i.split(" ")
}
foreach ($j in $line_array){
$multi_array += ,#($j.split("="))
}
foreach ($k in $multi_array){
$my_hash.add($k[0],$k[1])
}
$Sender_IP = $my_hash.Get_Item("sender-ip")
$eventList = #()
Get-EventLog "Security" -computername $Sender_IP `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| Select-Object -First 2 `
| foreach-Object {
$row = "" | Select UserName, LoginTime
$row.UserName = $_.ReplacementStrings[5]
$row.LoginTime = $_.TimeGenerated
$eventList += $row
}
$userId = $eventList[0].UserName
$userId
For instance, I invoke the script on commandline with
script.ps1 "sender-ip=10.10.10.10"
The first time I run it, it outputs the user's Window's logon name
The second time I run the same script with same input, it outputs the same service account I used to run the powershell script with
And when I try to run same script with same input, I get the output of this same service account.
~~~~~~~
Next, I try to run the script with another IP address
First time I run the script it outputs the Window's logon name
Second time I run the script, it outputs that same service account from which the powershell script is running
~~~~~~~
This seems to be a pattern. First time script it run, it return correct input, second time it is run, it returns the service account.
Why is this happening?
How to make the script always return the correct output no matter how many times it is invoked?
How to troubleshoot this?
This is because of how your script gets the information about the last logged on user.
You are getting the last logged on user from the security event log. This logs everyone who "logs on" to the computer... including accesses by WMI, service accounts, etc.
What's happening is:
Before Script Runs
Contoso\User1 logs onto computer
EventID 4624 - Logon Success - Contoso\User1 is Logged
Run Script the First time
Script runs as Contoso\ServiceAccount
Script access computer Via WMI to pull Security Event Log
Security Event Log shows last logged on user was Contoso\User1
EventID 4624 - Logon Success - Contoso\ServiceAccount is Logged
EventID 4634 - Logoff Success - Contoso\ServiceAccount is Logged
Run Script the Second time
Script runs as Contoso\ServiceAccount
Script access computer Via WMI to pull Security Event Log
Security Event Log shows last logged on user was Contoso\ServiceAccount
EventID 4624 - Logon Success - Contoso\ServiceAccount is Logged
EventID 4634 - Logoff Success - Contoso\ServiceAccount is Logged
This is because in order to access WMI, you have to authenticate on the computer. Essentially, WMI uses your service account to "log onto" the computer, access the information that it needs, returns the information, and logs off.
This is why you are getting the weird results.
To fix this, you have 3 options:
1.Continue to use the same script to pull out the event log entries. Add code to Filter out the service account name. i.e. use this to get the username:
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Then use the "Where -FilterScript" to filter out the user that the script is running as.
The only downside to this method, is that there could be a lot of other service accounts that are running various scheduled tasks, or startup scripts that could change who the "last" logged on user was. It may be better to pull the last 5 logged on users, and then you would have a better idea of what's going on.
2.Use this code to get the currently logged on user:
(gwmi -class win32_computerSystem -computer "ComputerName").username
3.A different and unique way of getting the last logged on user is to use the last write access time on the user profile file (ntuser.dat). Typically only a user logging in "Interactively" will get have a user profile created.
(Get-ChildItem C:\users\*\ntuser.dat -Force | select #{e={(Split-path $_.Directory -Leaf)}},last* | sort lastwritetime -Descending