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");
}