title: Running commands as logged on user (remotely)
body: <p>Thought I would share this quick function I made for myself, feel free to adapt it and improve it according to your needs.</p>
  
  <p>Sometimes you want to run commands as the logged on user of a remote computer.</p>
  
  <p>As you know, some commands show output for the user who runs it and if you run the same command with Invoke-Command, it won't return the user's information, but yours). Get-Printer is an example amongst many others.</p>
  
  <p>There is no easy, quick way of running commands as the logged on user natively without any third-party apps like PsExec or others so I made this quick function that uses VBS, PS1 and Scheduled Task to make it happen.</p>
  
  <p>It runs completly silently for the user (thanks to the VBS) and the output is shown in your console. Please note it assumes the remote computer has a C:\TEMP.</p>
  
  <p>Created in a Windows 10, powershell v 5.1.17763.503 environement.</p>
  
  <p>I don't pretend it's final and perfect, it's the simplest way I found to do what is needed and I just wanted to share it with you guys as it can be very useful!</p>
  
  <p>Check the comments for explanation of the code and feel free to use it as you wish. Please share your version as I'm curious to see people improve it. A good idea would be to make it support multiple computers, but as I said it's a quick function I did I don't have too much time to put into refining it.</p>
  
  <p>That being said, I had no problems using it multiple times as is :)</p>
  
  <p>*Output returned is in form of a string, if you want to have a proper object, add '| ConvertFrom-String' and play with it :)</p>
  
  <p>PLEASE NOTE: The surefire way of grabbing the username of who is currently logged on is via QWINSTA (since Win32_ComputerSystem - Username is only reliable if a user is logged on LOCALLY, it won't be right if a user is using RDP/RemoteDesktop). So this is what I used to grab the username, however, please note that in our french environement the name of the username property in QWINSTA is "UTILISATEUR",so you have to change that to your needs (english or other language) for it to work. If I remember correctly, it's "USERNAME" in english.</p>
  
  <p>On this line:</p>
  
  <pre><code>$LoggedOnUser = (qwinsta /SERVER:$ComputerName) -replace '\s{2,22}', ',' | ConvertFrom-Csv | Where-Object {$_ -like "*Acti*"} | Select-Object -ExpandProperty UTILISATEUR
  </code></pre>
  
  <p>See code in the answer below.</p>