Steve Ayers
Steve Ayers

Reputation: 86

Calling Get-Smbshare in C#

I am currently trying to use c# to call the Get-SMBShare which can be used in Powershell... however, it's throwing this error:

Exception:Caught: "The term 'Get-SMBShare' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." (System.Management.Automation.CommandNotFoundException) A System.Management.Automation.CommandNotFoundException was caught: "The term 'Get-SMBShare' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." Time: 25/10/2015 19:17:59 Thread:Pipeline Execution Thread[6028]

My first language is PowerShell, so I'm trying to translate a GUI tool from PowerShell to C#, and the tool uses hundreds of PS commands - is there something I should be calling? I'm testing things out in console here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        private static void GetShareNames()
        {
            // Call the PowerShell.Create() method to create an 
            // empty pipeline.
            PowerShell ps = PowerShell.Create();

            ps.AddCommand("Get-SmbShare");

            Console.WriteLine("Name                 Path");
            Console.WriteLine("----------------------------");

            // Call the PowerShell.Invoke() method to run the 
            // commands of the pipeline.
            foreach (PSObject result in ps.Invoke())
            {
                Console.WriteLine(
                        "{0,-24}{1}",
                        result.Members["Name"].Value,
                        result.Members["Path"].Value);
            } // End foreach.
            Console.ReadLine();
        } // End Main.
        static void Main(string[] args)
        {
            GetShareNames();
        }
    }
}

Upvotes: 1

Views: 1289

Answers (1)

Keith Hill
Keith Hill

Reputation: 201882

You need to import the module first. Stick in this line before you try to execute the Get-SmbShare command:

ps.AddCommand("Import-Module").AddArgument("SmbShare");
ps.Invoke();
ps.Commands.Clear();

ps.AddCommand("Get-SmbShare");

Another way is to initialize the runspace with the SmbShare module pre-loaded e.g.:

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new[] {"SmbShare"} );
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();     
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;

Upvotes: 3

Related Questions