Overview
After speaking with another user in the discussion board about how they could check for a signed in user session before provisioning another activity, I created the code explained below. I can see some value from such a requirement in provisioning accounts; however, it may make more sense to check for any other activity sessions having been provisioned for this than a logged in user. I may create an alternative script that checks Netwrix for any other provisioned sessions before allowing you to continue, but for now, this accomplishes the task as described in the post. Maybe some others can also get some value from it.
I have only briefly tested this in a very narrow scope, so as always, do your own research and testing before running code from a stranger on the internet!
Description
The below code will pull the account configured in the activity and see if there are any currently logged in sessions by that account, on the target resource. I would suggest putting this script as a custom step in your activity before any other assignments since it will cause a deprovision if a matching logon session is found. This code could likely be slightly better expanded to specifically check for the interactive logon sessions, but for what was described in the discussion post, I wanted to keep it vague enough to work across any circumstance.
#Checks for any currently logged in session by account used by activity and if found, error's out activity causing it to deprovision.
$activitySession = Get-SbPAMActivitySession -Id $SessionId
$logonAccount = $activitySession.loginaccountname
$targetHost = Get-SbPAMHost -Id $HostId
$session = New-SbPAMPSSession -RemoteHost $targetHost -Credential (Get-PSCredential -Credentials $Credentials)
if ($null -ne $session) {
try
{
Add-SbPAMActionLog -Type Info -Message "Connecting to $($targetHost.DnsHostName)"
$userSessions = @(Invoke-Command -Session $Session -ScriptBlock {
Get-CimInstance -class win32_LoggedOnUser
})
}
finally
{
# Close the session
Remove-PSSession -Session $session
}
Add-SbPAMActionLog -Type Info -Message "Retrieved $($userSessions.count) logon sessions"
Add-SbPAMActionLog -Type Info -Message "Checking if session exists for $logonAccount ..."
foreach ($session in $userSessions) {
$sessionLogonAccount = $session.Antecedent.Domain + '\' + $session.Antecedent.Name
if ($sessionLogonAccount -ieq $logonAccount) {
Add-SbPAMActionLog -Type Error -Message "Found logon session present for $logonAccount!"
exit(1)
}
}
Add-SbPAMActionLog -Type Info -Message "Found no current logon session present for $logonAccount"
}
Sample Output
See this below sample log output for when a matching logon session is found: