#Getting user SID from an event $usrSID=(Get-WinEvent -LogName 'Microsoft-Windows-TerminalServices-RemoteConnectionManager/Admin' -MaxEvents 1 -FilterXPath 'Event[System[EventID=20491]]').Properties[0].value $RDShName = $env:COMPUTERNAME $usr = (Get-ADUser $usrSID).name if (($usrSID -ne $null) -and $usrSID.Contains("S-1-5-21-2867085864-812408830-756674219")) { # Run script on server where save UPD $session_fs = New-PSSession -ComputerName FS01 $FileStatus = Invoke-Command -Session $session_fs -ScriptBlock { $usr=$Using:usr $SID=$Using:usrSID $RDName=$Using:RDShName sleep -Seconds 15 # Get open UPD $OpenFiles=Get-SmbOpenFile | ? {($_.ShareRelativePath -like "*$SID*")-and ($_.Path -like "*\UPD\*")} if ($OpenFiles -ne $null) { $StatusFile = "open" Add-Content -Path "C:\UPDstatus.txt" -Value "$(Get-Date -Format "dd.MM.yyyy HH:mm:ss"); log out from rds:$RDName ;UserName: $usr; SID: $SID; UPD file was open; ClientUserName: $($OpenFiles.ClientUserName)" # Close open UPD $OpenFiles | Close-SmbOpenFile -Force Return $StatusFile } else { Add-Content -Path "C:\UPDstatus.txt" -Value "$(Get-Date -Format "dd.MM.yyyy HH:mm:ss"); log out from rds:$RDName ;UserName: $usr; SID: $SID; UPD file NOT open" } } Remove-PSSession $session_fs # Clean up user profile $wmiUserProfile=Get-WMIObject -class Win32_UserProfile | ? {($_.LocalPath).contains($usr) -and ($_.SID -eq $usrSID) -and ($_.Special -eq $False) -and ($_.Loaded -eq $False)} if ($wmiUserProfile -ne $null) { $wmiUserProfile | Remove-WmiObject Add-Content -Path "c:\RegistryClearEvent.txt" -Value "$(Get-Date -Format "dd.MM.yyyy HH:mm:ss"); User: $usr; SID: $usrSID; clear old User data in Profile" } else { Add-Content -Path "c:\RegistryClearEvent.txt" -Value "$(Get-Date -Format "dd.MM.yyyy HH:mm:ss"); User: $usr; SID: $usrSID; Not find User data in Profile" } }