1

I am trying to use MDT from c# like I can already do with powershell when importing MicrosoftDeploymentToolkit.psd1. For example I can run the command Get-MDTPersistentDrive directly from powershell without problem.

But I can't find a way to do the same thing from c#, I tried to include directly the Microsoft.BDD.PSSnapIn.dll (which was basically what was doing "MicrosoftDeploymentToolkit.psd1") then I could access to the GetPersistent class but an error message informed me that I cannot directly invoke a PSCMDlet.

I then tried to use the PowerShell class

var ps = PowerShell.Create();
ps.AddScript(@"import-module C:\...\MicrosoftDeploymentToolkit.psd1");
ps.Invoke();

ps.AddCommand("Get-MDTPersistentDrive");
var result = ps.Invoke();

But I receive this exception

The term 'Get-MDTPersistentDrive' is not recognized as the name of a cmdlet, function, script file, or operable program

I then tried to do this

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { @"C:\...\MicrosoftDeploymentToolkit.psd1" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-MDTPersistentDrive");

var result= ps.Invoke();

and I receive the error

Object reference not set to an instance of an object

I'm really lost, I don't get what they mean with this error, If you could show me where I'm wrong, or a way to execute PSCmdlet from c# or even better directly how to control MDT that would be awesome.

Gatoyu
  • 642
  • 1
  • 6
  • 22
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Smartis has left SO again Aug 31 '16 at 13:05

0 Answers0