-1

I want to execute the PowerShell script without SDK. In my project, I have to execute the PowerShell script and also want to create an EXE file for the same. But the problem is:

  • When I remove Microsoft.PowerShell.SDK then the script is not executed and gives an error but creates an exe file. Error is "Cannot load PowerShell snap-in Microsoft.PowerShell.Diagnostics because of the following error: Could not load file or assembly".

  • When the above package is not removed from the project then the script is working fine but it gives an error while creating an exe file.

Please share your suggestion.

Here is my code:

string readLocationFile = File.ReadAllText(@"gravity_location.ps1");
using (PowerShell powerShell = PowerShell.Create())
{
    powerShell.AddScript(readLocationFile);
    powerShell.AddParameter("name", _locationName.Text);
    powerShell.AddParameter("targetPath", filePath);
    powerShell.Invoke();
}

1 Answers1

0

You can use System.Management.Automation which is the core of the PowerShell SDK like this

using System.Management.Automation;
using System.Management.Automation.Runspaces;
//...
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();

//Here's how you add a new script with arguments
Command myCommand = new Command("your/script/file/path.ps1");
CommandParameter testParam = new CommandParameter("key","value"); //e.g. "-Path" "value" 
myCommand.Parameters.Add(testParam);

pipeline.Commands.Add(myCommand);

// Execute PowerShell script
results = pipeline.Invoke();

Detailed information about the packages. https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/choosing-the-right-nuget-package?view=powershell-7.2

Another post about the topic: Execute PowerShell Script from C# with Commandline Arguments

tomwaitforitmy
  • 509
  • 3
  • 16
  • If I am using 'System.Management.Automation' this package then it required SDK, without SDK it gives an error. – Pratiksha Pansara Aug 01 '22 at 10:01
  • Did you check https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/choosing-the-right-nuget-package?view=powershell-7.2 for details about when you need which? I am not using `Microsoft.PowerShell.SDK` anywhere. – tomwaitforitmy Aug 01 '22 at 11:18
  • This is what I am using: ``. Not sure if they are internally the same or not. – tomwaitforitmy Aug 01 '22 at 11:23