0

I'm trying to get the status of a backup (Windows Server 2012R2) from a C# WinForm (.Net 6).

If I open up Powershell on my server and type Get-WBSummary, then I get the last backup info ... perfect.

But when I try from my C#, then I get this error:

The term 'Get-WBSummary' is not recognized as a name of a cmdlet, function, script file, or executable program.\r\nCheck the spelling of the name, or if a path was included, verify that the path is correct and try again.

Here's my testcode:

using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace PowershellBackupResultTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                PowerShell ps = PowerShell.Create();
                Runspace runSpace = RunspaceFactory.CreateRunspace();
                runSpace.Open();
                ps.Runspace = runSpace;
                await ps.AddCommand("Set-ExecutionPolicy").AddParameter("Scope", "CurrentUser").AddParameter("ExecutionPolicy", "Unrestricted").InvokeAsync().ConfigureAwait(false);
                ps.AddCommand("Get-WBSummary");
                if (ps.HadErrors)
                {
                    foreach (ErrorRecord err in ps.Streams.Error)
                    {
                        Console.WriteLine(err);
                    }

                }
                else
                {
                    var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
                    foreach (var item in pipelineObjects)
                    {
                        Console.WriteLine(item.BaseObject.ToString());
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex}");
            }
        }
      
    }
}

I've added following top-level Nugets:

  • Microsoft.PowerShell.SDK
  • System.Management.Automation

What am I missing?

MojoDK
  • 4,410
  • 10
  • 42
  • 80
  • compare the PDModulePath from cmd.exe >SET with response in c# : string path = Environment.GetEnvironmentVariable("PSMODULEPATH"); The cmdlet has to be loaded in one of the path folders. – jdweng Nov 03 '22 at 20:45

0 Answers0