Calling Powershell ps1 file using System.Management.Automation [duplicate] - c#

This question already has an answer here:
Calling ps script file in c# using automation dll
(1 answer)
Closed 5 years ago.
I have the following c# code:
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
var runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
// create a pipeline and feed it the script text
var pipeline = runspace.CreatePipeline();
var command = new Command(#". .\MyScript.ps1");
command.Parameters.Add("MyParam1", value1);
command.Parameters.Add("MyParam2", value2);
pipeline.Commands.Add(command);
pipeline.Invoke();
runspace.Close();
But I am getting the error Powershell ps1 file “is not recognized as a cmdlet, function, operable program, or script file.”
MyScript.ps1 is copied to the bin folder so it is at the same level as the running program.
I found this Powershell ps1 file "is not recognized as a cmdlet, function, operable program, or script file."
But it did not solve the problem. Any idea what else could cause this error?

Problem is likely that your application inherits its working directory from the parent process, so you can't predict that . refers to the directory in which the executable resides.
You could construct the full path to the script with something like:
using System.Reflection;
using System.IO;
// ...
string exePath = Assembly.GetExecutingAssembly().Location;
string exeFolder = Path.GetDirectoryName(exePath);
string scriptPath = Path.Combine(exeFolder,"MyScript.ps1");
var command = new Command(". " + scriptPath);

Related

C# Powershell executing custom function from script file

I have a powershell script file that contains multiple functions. I would like to call one of the functions using C#. When I invoke my command, it throws an error
"The term 'LogIn-System' 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."
Here is some sample code:
using (PowerShell powerShellInstance = PowerShell.Create())
{
powerShellInstance.Runspace = runSpace;
powerShellInstance
.AddScript("myfunctions.ps1")
.Invoke();
powerShellInstance
.AddCommand("LogIn-System")
.AddParameter("SystemName", "Connect");
Collection<PSObject> PSOutput = await Task.Run(() =>
powerShellInstance.Invoke());
}
You have to use two separate invokes. One to import the module, the second is your script. Since Import-Module is a Command from a previous loaded module, call it with AddCommand. Specify the Module name to import with the AddParameter function. For example:
PS
.AddCommand("Import-Module")
.AddParameter("Name", "ExchangeOnlineManagement")
.Invoke();
PS
.AddScript([your script name])
.Invoke();

How to create powershell script dynamically from c# based on input params without having physical script file in machine

I know we can can run physical powershell script from c# but how to create powershell script file itself dynamically based on input params.
Kindly suggest.
you can execute powershell script/ commands directly from your c# project.
you'll need to add a reference to system.managment.automation dll in project's references.
example:
function that will take script as a string , execute it and then returns a result:
private string RunScript(string script)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipline = runspace.CreatePipeline();
pipline.Commands.AddScript(script);
pipline.Commands.Add("Out-String");
Collection<PSObject> results = pipline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach(PSObject pSObject in results)
{
stringBuilder.AppendLine(pSObject.ToString());
}
return stringBuilder.ToString();
}
function call be like:
Console.WriteLine(RunScript("Your Powershell Script"));
you can check out the full code examples on github - PowershellCommand-CSharp

git' is not recognized while using c# (web application)

I want to execute the power shell logic using c#(web application) but i'm getting the issue
The term 'git' 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.
I have added the git path in environmental variables and able to execute the same powershell logic from powershell window without any issues.
My powershell script:
function CheckoutTheCode($checkoutRepoUrl, $checkoutDirectory, $checkoutBranch)
{
[hashtable]$Return = #{}
try
{
# Cloning
git clone --single-branch -b $checkoutBranch $checkoutRepoUrl $checkoutDirectory
$Return.Status = $true
$Return.Message = "Success"
}
catch
{
$Return.Message = $Error[0].Exception
$Return.Status = $false
}
Return $Return
}
$checkoutDirectory = "local directory for checkout"
$checkoutRepoUrl = "bit bucket repo url"
$checkoutBranch = "branch version"
CheckoutTheCode $checkoutRepoUrl $checkoutDirectory $checkoutBranch
My c# code:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("PowerShell script");
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
}
In My case the issue is I have added the system environment variable after the c# web application is opened in visual studio.
When i have closed the visual studio and opened again, it's working fine.

Executing cmdlet Get-ClusterGroup from C#

Hi I'm trying to execute the Get-ClusterGroup cmdlet from C# 4.0. I've used the following code
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "failoverclusters"});
Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss);
myRunSpace.Open();
Pipeline pipeLine = myRunSpace.CreatePipeline();
Command myCommand = new Command("Get-ClusterGroup");
pipeLine.Commands.Add(myCommand);
Console.WriteLine("Invoking Command");
Collection commandResult = pipeLine.Invoke();
foreach (PSObject resultObject in commandResult)
{
Console.WriteLine(resultObject.ToString());
}
myRunSpace.Close();
But getting the following error
The term 'Get-ClusterGroup' 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.
It will be great if someone can show me the where I'm missing the logic or where is the problem in my code
Get-ClusterGroup is a Powershell Commandlet, not an .exe file. You can invoke Powershell commands from .NET using the System.Management.Automation.PowerShell class, as described on MSDN here: http://msdn.microsoft.com/en-us/library/system.management.automation.powershell(v=vs.85).aspx

Adding a Batch/Powershell file to a compilation (Build) C# Powershell

I'm working on a c# project where i'm trying to run powershell scripts, output them to a CSV and read the CSV and output it to a Checked list box.
I've added a powershell file as a resource with Build Action 'Compile' and Copy to output directory 'Do Not Copy'.
The basic content of the file is :
Get-CimInstance -Query "SELECT * from Win32_Service where name LIKE 'sql%'" | select Name, State , StartMode | convertto-csv > proctest.csv
i try to access this file using this string
string ps_path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\GetSvc.ps1";
The PS code i use is
RunspaceConfiguration runspaceconfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceconfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command mycommand = new Command(ps_path);
pipeline.Commands.Add(mycommand);
pipeline.Invoke();
runspace.Close();
This works fine during compilation but when i build an exe and try to run it, i get an error saying the GetSvc.ps1 file is not found.
How do i make the file a part of the build ?!
Make the build action for the script be Embedded Resource. Then take a look at lines 149-155 on how to extract the script inside the C# exe. In this example, I had zipped the script to compact it. If you skip that step then you can remove line 152 and in line 153 use stream instead of gZipStream.

Categories