1

I want to use a Invoke-RDUserLogoff cmdlet to logoff users on remote computer. This cmdlet works well when is submitted using PowerShell. However, every time I try to execute it using the below code I get a "Invoke-RDUserLogoff is not recognized as the name of a cmdlet.....". Any clue or help will be appreciate it. Thanks!

System.Management.Automation.PowerShell psinstance = System.Management.Automation.PowerShell.Create();
            string errorMesg = string.Empty;
            //string result = string.Empty;
            string command = "";

            command = @"Invoke-RDUserLogoff  -HostServer "   + computerNameTB.Text + " -UnifiedSessionID " + sessionIDTB.Text + " -Force";
            
            psinstance.AddCommand(command);
            //Make sure return values are outputted to the stream captured by C#
            psinstance.AddCommand("out-string");
            PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();

            psinstance.Streams.Error.DataAdded += (object sender1, DataAddedEventArgs e1) =>
            {
                errorMesg = ((PSDataCollection<ErrorRecord>)sender1)[e1.Index].ToString();
            };

            //IAsyncResult result = psinstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
            IAsyncResult result = psinstance.BeginInvoke();

            //wait for powershell command/script to finish executing
            psinstance.EndInvoke(result);
            
            StringBuilder sb = new StringBuilder();

            foreach (var outputItem in outputCollection)
            {
                sb.AppendLine(outputItem.BaseObject.ToString());
            }

            if (!string.IsNullOrEmpty(errorMesg))
            {
                MessageBox.Show(errorMesg, "Logoff Users");

            }
            else
            {
                MessageBox.Show(sb.ToString(), "LogoffUsers app");

            }
JC Nunez
  • 187
  • 2
  • 12
  • Try adding parameters to the command by using the System.Management.Automation.PSCommand.AddParameter method as described in "Add Parameters" section [https://learn.microsoft.com/en-us/powershell/scripting/developer/hosting/windows-powershell-host-quickstart?view=powershell-7.3#addparameter](https://learn.microsoft.com/en-us/powershell/scripting/developer/hosting/windows-powershell-host-quickstart?view=powershell-7.3#addparameter) – Angel Dinev Nov 22 '22 at 18:55
  • Thanks Angel, but it did not work :( – JC Nunez Nov 22 '22 at 19:13
  • 1
    Microsoft states "...While the default runspace loads all of the core Windows PowerShell commands..." Probably you need to explicitly import the module containing this cmd - RemoteDesktop or RDMgmt. Please look at the Note section in [https://stackoverflow.com/a/66280138/8327106](https://stackoverflow.com/a/66280138/8327106). Good luck! – Angel Dinev Nov 22 '22 at 19:42
  • I don't want to bother you again Angel but I must be doing something wrong and I don't know what it is.. I am trying to Import the module RemoteDesktop but I am getting a message "...was not loaded because no valid module was found in any module directory". Then, I did "get-module -listavailable remotedesktop | select-object path" to get the path to the module which is found in C:\Windows\system32\WindowsPowerShell\v1.0\Modules\RemoteDesktop\RemoteDesktop.psd1. I ran the code again and I got the same results. Any clue? – JC Nunez Nov 23 '22 at 13:23
  • I have installed Microsoft.PowerShell.SDK 7.3.0 and tested few commands which are available for me to run on my Win11 Home ed. : **Invoke-WebRequest** and *whoami*. Both work OK. I don't have RemoteDesktop module on my humble Win11-Home and cannot test for any of its cmds. See this [Calling PowerShell cmdlet from C# throws CommandNotFoundException](https://stackoverflow.com/questions/22488780/calling-powershell-cmdlet-from-c-sharp-throws-commandnotfoundexception) for any additional clues what might be the problem. Good luck! – Angel Dinev Nov 23 '22 at 17:41
  • See also this one too [Error while running RemoteDesktop commandlets in powershell from C#](https://stackoverflow.com/questions/51242111/error-while-running-remotedesktop-commandlets-in-powershell-from-c-sharp). RD cmds may require a more complex invokation. Good luck! – Angel Dinev Nov 23 '22 at 17:52
  • Another hint I think worth to try is checking the project settings: found few claims that changing the target platform cpu to x64 from x86 might fix locating the proper modules. – Angel Dinev Nov 23 '22 at 20:10
  • Check this one: [Import-Module does not work in c# powershell command](https://social.msdn.microsoft.com/Forums/vstudio/en-US/55694b2e-4fe2-4ffa-9cf5-73bb607fa51b/importmoud-dose-not-work-in-c-powershell-command?forum=csharpgeneral) – Angel Dinev Nov 23 '22 at 20:26
  • 1
    Hi Angel, thanks a lot for your help. I had to attend another business and I am coming back to this code. It is working now but I am getting now an "access was denied" error trying to logoff users even running the app as admin. Let se what I can do to fix it. Thanks! – JC Nunez Dec 09 '22 at 14:05
  • 1
    Angel, it is ok, It is working fine now thanks to your help. The app is just falling to logoff a session id 0 (access is denied) but is able to logoff any other session id. Wonder why that behavior with session id 0. Thanks!! – JC Nunez Dec 09 '22 at 15:49
  • Hi JC, glad you've made it... I guess changing tha target platform did the trick. If so, could I post it as an answer to fully complete the question. It may be of use to someone else in the future? – Angel Dinev Dec 12 '22 at 12:29
  • 1
    Yes Angel, no problem. You can go ahead and I will post my solution :) – JC Nunez Dec 13 '22 at 15:15

1 Answers1

0

A hint I think worth trying is checking the project settings: found few claims that changing the target platform cpu to x64 from x86 might fix locating the proper modules please see: Import-Module does not work in c# powershell command Good luck!

Angel Dinev
  • 399
  • 4
  • 13