In this form it has nothing to do with powershell (those are plain executable files). It could be run also as batch file (Both cmdkey and mstsc are executables and you don't have .\ before them or starting them via invoke-command or other means).
I will use the variables from your code and powershell (I'm not adjusting it to run via invoke-command or others. That is out of the scope of this question and would be good practice for you):
cmdkey /generic:TERMSRV/$server /user:$user /pass:$serverPassword
mstsc /v:$server /f
To check if the you have connected session in the Windows Event logs - via Get-Winevent:
Get-Winevent -comp $server -FilterHashtable @{Logname='security'; ID=4624; StartTime=(Get-Date).addMinutes(-10)} | where {$_.properties[8].value -eq 10 -and $_.properties[5].value -eq $user}
Description of the command (skipping the obvious):
-FilterHashtable
Logname='security' - it is the Windows Log group Security (you have
Application, Security, Setup, System and Forwarded events
in Windows 7)
ID=4624 - That is an ID of the security event 4624: An account was successfully logged on
StartTime=(Get-Date).addMinutes(-10)} subtracting 10 minutes from the current time (note: you should adjust this according to your needs)
then further filtering with |
$_.properties[8].value -eq 10 RDP (alias RemoteInteractive) session is type 10.
Here is the type table:
╔═════════════════╦═════════════════════════════════════════════════════════════════════════════╗
║ Logon Type ║ Description ║
╠═════════════════╬═════════════════════════════════════════════════════════════════════════════╣
║ 2 ║ Interactive (logon at keyboard and screen of system) ║
║ 3 ║ Network (i.e. connection to shared folder on this computer from elsewhere ║
║ ║ on network) ║
║ 4 ║ Batch (i.e. scheduled task) ║
║ 5 ║ Service (Service startup) ║
║ 7 ║ Unlock (i.e. unnattended workstation with password protected screen saver) ║
║ 8 ║ NetworkCleartext (Logon with credentials sent in the clear text. Most often ║
║ ║ indicates a logon to IIS with "basic authentication") ║
║ 9 ║ NewCredentials such as with RunAs or mapping a network drive with alternate ║
║ ║ credentials. This logon type does not seem to show up in any events. If ║
║ ║ you want to track users attempting to logon with alternate credentials see ║
║ ║ security Type ID 4648. MS says "A caller cloned its current token and ║
║ ║ specified new credentials for outbound connections. The new logon session ║
║ ║ has the same local identity, but uses different credentials for other ║
║ ║ network connections." ║
║ 10 ║ RemoteInteractive (Terminal Services, Remote Desktop or Remote Assistance) ║
║ 11 ║ CachedInteractive (logon with cached domain credentials such as when ║
║ ║ logging on to a laptop when away from the network) ║
╚═════════════════╩═════════════════════════════════════════════════════════════════════════════╝
-and $_.properties[5].value -eq $user last but not the least, filtering based on the $user variable