Does any one have a power shell script that would the get user logged into a windows VM via a SAM script?
What is your goal with this script?
Are you trying to log which users are logged on a VM? Are you trying to log and alert if a specific account is logged onto a VM, or are you trying to log and alert if a specific number of users are logged onto a VM?
I know its not what you're looking for, but has the groundwork for getting logged in sessions. This script works awesomely for us to get an email listing sessions logged in.
# Import the Active Directory module for the Get-ADComputer CmdLetImport-Module ActiveDirectory
# Get today's date for the report$today = Get-Date$arrayofStringsNonInterestedIn = "console" , "RDP" , "services"
# Setup email parameters$subject = "ACTIVE SERVER SESSIONS REPORT - " + $today$priority = "Normal"$smtpServer = "mail.yourcompany.com"$emailFrom = "RDPSessions@yourcompany.com"$emailTo = "you@yourcompany.com"
# Create a fresh variable to collect the results. You can use this to output as desired$SessionList = "ACTIVE SERVER SESSIONS REPORT - " + $today + "`n`n"
# Query Active Directory for computers running a Server operating system$Servers = Get-ADComputer -Filter {OperatingSystem -like "*server*"}
# Loop through the list to query each server for login sessionsForEach ($Server in $Servers) {$ServerName = $Server.Name
# When running interactively, uncomment the Write-Host line below to show which server is being queriedWrite-Host "Querying $ServerName"
# Run the qwinsta.exe and parse the output$queryResults = (qwinsta /server:$ServerName | foreach { (($_.trim() -replace "\s+",","))} | ConvertFrom-Csv)# Pull the session information from each instanceForEach ($queryResult in $queryResults) {$RDPUser = $queryResult.USERNAME$sessionType = $queryResult.SESSIONNAME$State=$queryResult.StateIf ($queryResult.ID -eq "Disc") {$RDPUser = $queryResult.Sessionname$SessionType=" "$State=$queryResult.ID}# We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a numberIf (($RDPUser -match "[a-z]") -and ($RDPUser -ne $NULL) -and ($RDPUser -ne "Disc")) {# When running interactively, uncomment the Write-Host line below to show the output to screenWrite-Host $ServerName logged in by $RDPUser on $sessionType$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType}}}
# When running interactively, uncomment the Write-Host line below to see the full list on screen#$SessionListget-content $sessionlist | where {$arrayofStringsNonInterestedIn -notcontains $_}Write-host $SessionList
$SessionList2 = ""ForEach($l in $SessionList.split("`n")){if ($l.Trim().Equals("")){continue}if ($l.Contains("services")) {continue}if ($l.Trim().EndsWith("on")) {$SessionList2 += $l + "`n"}}
Write-host $SessionList2# Send the report emailSend-MailMessage -To $emailTo -Subject $subject -Body $SessionList2 -SmtpServer $smtpServer -From $emailFrom -Priority $priority