What is the reference for PowerShell in .NET? - c#

I tried to run a PowerShell script in C#. But it throws and error :
PowerShell doesn't available in current context.
I searched in google but i didn't get the solution, please help. This is my code :
string text = System.IO.File.ReadAllText(#"C:\Program Files (x86)\Backup Reporter\Required\edit_website.ps1");
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript(text);
if (PowerShellInstance.Streams.Error.Count > 0)
{
Console.Write("Error");
}
Console.ReadKey();
}

Download and Add the packages of System.Management.Automation and System.Management.Automation.Runspaces from VS Nuget Manager to your project.
https://powershell.org/forums/topic/executing-powershell-from-c/

PowerShell class exists in Windows PowerShell SDK 1.1.0 that you to your project with this NuGet package : https://www.nuget.org/packages/System.Management.Automation/
PM> Install-Package System.Management.Automation -Version 6.2.0

You need to download System.Management.Automation and attach it to your project:
https://www.nuget.org/profiles/PowerShellTeam

Related

Pipeline type could not be found (using .Net 4.7.2)

I am currently trying to run a simple PowerShell script through WinForms on Visual Studio 2022, using .Net Framework 4.7.2. I followed an example I found online, the code shown further below.
I added System.Management.Automation to NuGet Packages, as was recommended but the 'Runspace' type was not recognised.
Following this I read that adding PowerShellStandard.Library to Nuget Packages would allow it to be recognised, and it was. Unfortunately, the 'Pipeline' type was then not recognised.
I tried to downgrade the System.Management.Automation, but I could not get it to work. I then created a .Net Core version (.Net 6.0) and the code below worked (after adding System.Managerment.Automation 7.2.7 to Nuget).
Any ideas why Pipeline didn't work on my .Net Framework solution? Thank you in advance for any help!
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Windows.Forms;
namespace CallPowerShellScriptPractice
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnRunScript_Click(object sender, EventArgs e)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
Command command = new Command(#"C:\Practice\PowerShellPractice\hello.ps1");
pipeline.Commands.Add(command);
pipeline.Invoke();
runspace.Close();
MessageBox.Show("PowerShell script being executed..");
}
}
}
None of version of the package System.Management.Automation are compatible with .NET Framework.
If you install this package in a .NET Framework project :
dotnet new console --name Demo.Shell --framework netcoreapp3.1 --target-framework-override net472
cd Demo.Shell
dotnet add package System.Management.Automation --version 6.1.6
You get the error :
...
error: NU1202: Package System.Management.Automation 6.1.6 is not compatible with net472 (.NETFramework,Version=v4.7.2). Package System.Management.Automation 6.1.6 supports: netcoreapp2.1 (.NETCoreApp,Version=v2.1)
error: NU1202: Package System.Management.Automation 6.1.6 is not compatible with net472 (.NETFramework,Version=v4.7.2) / win7-x86. Package System.Management.Automation 6.1.6 supports: netcoreapp2.1 (.NETCoreApp,Version=v2.1)
error: Package 'System.Management.Automation' is incompatible with 'all' frameworks in project '.\Demo.Shell\Demo.Shell.csproj'.
This library can't be installed and its types can't be used.
About PowerShellStandard.Library, it has the types RunspaceFactory and Runspace, but not Pipeline.
However it's a library to develop PowerShell module. I don't think it can be used to execute a script.
The only solution I found to execute a PowerShell script from .NET Framework program, it's to use Process to call PowerShell like :
var processInfo = new ProcessStartInfo("powershell", "-NoLogo");
processInfo.Arguments = #"C:\t\hello.ps1";
processInfo.CreateNoWindow = false;
processInfo.UseShellExecute = false;
processInfo.WindowStyle = ProcessWindowStyle.Normal;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
var process = Process.Start(processInfo);
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.Error.WriteLine(e.Data);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();

How to get rid of this problem ( On adding a nuget packages from VSCode it says terminated with exit code: 1.)?

When I trying to add Nuget Packages by Nuget gallery extension from VS Code. It doesn't install the NuGet package.
Executing task: dotnet add /home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj package Microsoft.AspNetCore.Identity.EntityFrameworkCore -v 5.0.6 -s https://api.nuget.org/v3/index.json <
Determining projects to restore...
Writing /tmp/tmpIIHQRz.tmp
info : Adding PackageReference for package 'Microsoft.AspNetCore.Identity.EntityFrameworkCore' into project '/home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj'.
info : Restoring packages for /home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj...
error: Unable to load the service index for source https://api.nuget.org/v3/index.json.
error: The SSL connection could not be established, see inner exception.
error: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
Usage: NuGet.CommandLine.XPlat.dll package add [options]
Options:
-h|--help Show help information
--force-english-output Forces the application to run using an invariant, English-based culture.
--package Id of the package to be added.
--version Version of the package to be added.
-d|--dg-file Path to the dependency graph file to be used to restore preview and compatibility check.
-p|--project Path to the project file.
-f|--framework Frameworks for which the package reference should be added.
-n|--no-restore Do not perform restore preview and compatibility check. The added package reference will be unconditional.
-s|--source Specifies NuGet package sources to use during the restore.
--package-directory Directory to restore packages in.
--interactive Allow the command to block and require manual action for operations like authentication.
--prerelease Allows prerelease packages to be installed.
The terminal process "/bin/bash '-c', 'dotnet add /home/[user]/Public/Projects/yogihosting.com/Identity/Identity/Identity.csproj package Microsoft.AspNetCore.Identity.EntityFrameworkCore -v 5.0.6 -s https://api.nuget.org/v3/index.json'" terminated with exit code: 1.
Terminal will be reused by tasks, press any key to close it.
How can I get rid of this problem?
https://api.nuget.org/v3/index.json shows:#
Note: I'm using Ubuntu.
We may solve this issue by one of following process.
copy project to another folder or create new project to another destination.
It may cause, our file or folder is corrupted.
Reinstalling our software(s) like IDE or dotnet or both.
It may cause not to be installed correctly.
The final is so funny. Re-install your OS and then other softwares.

Is it possible to install a local version of a package at runtime and use said local package?

As part of trying to test a NuGet package with a Console application, is it possible to have the console application get the latest version of said NuGet package programmatically, and then use said package to call various methods and what not? This is the flow that I'm trying to achieve...
A NuGet package is created locally (already done as part of a build process)
A console application installs this package
The same console application calls a few methods that are inside this package (if this uses reflection insdie the console app to achieve this it isn't an issue)
How can this be achieved? I've tried the following code using the NuGet.Core & NuGet.Protocol NuGet packages...
// exception thrown for trying to resolving newtonsoft
IPackageRepository packageRepository = new NuGet.LocalPackageRepository(directoryPath);
PackageManager pm = new PackageManager(packageRepository, GetExecutingAssemblyDirectory());
pm.InstallPackage("package_id", SemanticVersion.Parse("package_version"));
NuGet.Common.ILogger logger = new Logger();
IEnumerable<LocalPackageInfo> packageInfos = LocalFolderUtility.GetPackagesV2(directoryPath, logger);
foreach (LocalPackageInfo lpi in packageInfos)
{
// no obvious way to actually install the package
}
// never more than zero packages
var localRepo = new LocalPackageRepository(directoryPath);
var packages = localRepo.GetPackages();
if (packages?.Count() > 0)
{
var packageManager = new PackageManager(localRepo, GetExecutingAssemblyDirectory());
packageManager.InstallPackage(packages.ElementAt(0).Id);
}
I haven't been able to get any of those pieces of code to work. Is this actually possible? Would I have to look at using 2 Console apps (one to install into the other, which then does the calling of methods), and if so how would this be done?

Using C# to execute Powershell command (azureVM)

I'm trying to develop a .Net form application to manage azure VMs in C# using Powershell cmdlets. I'll have to use the Azure module to get this working.
One of the cmdlet will be Add-AzureAccount
My question is how can I include this module (Azure) in C# project ?
In the comment section, #Prageeth Saravanan gave a useful link on how integrate PowerShell in C#.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
Quick example :
First I had to include these refs :
System.Management.Automation
System.Collections.ObjectModel
Note : You need to add a NuGet package for "Management.Automation". Just type "System.Management.Automation" you'll find it.
C# code:
//The first step is to create a new instance of the PowerShell class
using (PowerShell powerShellInstance = PowerShell.Create()) //PowerShell.Create() creates an empty PowerShell pipeline for us to use for execution.
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
powerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; $d; $s; $param1; get-service");
// use "AddParameter" to add a single parameter to the last command/script on the pipeline.
powerShellInstance.AddParameter("param1", "parameter 1 value!");
//Result of the script with Invoke()
Collection<PSObject> result = powerShellInstance.Invoke();
//output example : #{yourProperty=value; yourProperty1=value1; yourProperty2=StoppedDeallocated; PowerState=Stopped; OperationStatus=OK}}
foreach (PSObject r in result)
{
//access to values
string r1 = r.Properties["yourProperty"].Value.ToString();
}
}
Hope this helps!
We could use PowerShell cmdlets Import-module to add corresponding modules to the current session. We could use force parameter to re-import a module into the same session.
Import-module -name azure -force
The import thing is that the imported module need to be installed on the local computer or a remote computer. So if we want to execute Azure PowerShell cmdlets from C# project that we need to make sure that Azure PowerShell are installed. We can use install-module AzureRM or Azure more details please refer to the Get Started Azure PowerShell cmdlets. In the Azure VM, Azure PowerShell is installed by default.
About how to call PowerShell command or PS1 file using C# please refer to Prageeth Saravanan mentioned link or another SO Thread.

create nuget package fails with 'Path is not of a legal form'

In a post build step we create nuget packages. For some reasons this always fails on my machine, while it works on other developers machines.
The command executed is:
nuget.exe pack "$(ProjectPath)" -Properties Configuration=$(ConfigurationName) -OutputDir "$(ProjectDir)..\Apps"
The output i get is:
Packing files from ''.
Using 'Organisation.AppName.Modules.Kcs.nuspec' for metadata.
The path is not of a legal form.
For other developers the first line contains the directory. What can be the reason it is working differently on my box? Are there options i can set to change this behavior?
Edit:
I downloaded the nuget source and found the point things start to go wrong. With a small test program i can simulate it:
using System;
using Microsoft.Build.Evaluation;
namespace CheckTarget
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("usage: CheckTarget projectfile.csproj");
Console.WriteLine();
return;
}
string path = args[0];
var project = new Project(path);
Console.WriteLine("TargetDir = {0}", project.GetProperty("TargetDir") != null ? project.GetProperty("TargetDir").EvaluatedValue : string.Empty);
Console.WriteLine("TargetPath = {0}", project.GetProperty("TargetPath").EvaluatedValue);
Console.ReadKey();
}
}
}
On my machine the targetdir is null, on another machine the targetdir points to valid directory.
Use property Platform to -Properties parameter in nuget program
-Properties Platform=$(Platform)
where $(Platform) is one of your project platform (defined in csproj file, typically x86, 'Any CPU', ..).
ie in your case, run something like:
nuget.exe pack "$(ProjectPath)" -Properties Configuration="$(ConfigurationName)" Platform="$(Platform)" -OutputDir "$(ProjectDir)..\Apps"
Finally found the answer. This thread helped me locate the problem:
http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/d3c6e2de-1e87-49c2-b059-df074868e315/
On my machine there was an environment variable 'platform' with value 'BWS'. Deleted it and things are working!
I had the same problem basically it was an old nuget version that I carried in my source control, I deleted the .nuget folder then I uninstalled nuget from visual studio, by selecting
tools > extensions & updates,
select nuget & uninstall and then do the same process but for Installing it, just make sure you al searching in the "online" repository.
I had to update the Nuget Manager from Updates And Extensions. Restarted VS, and it worked fine.
For me the problem was that no .dll was inside the Debug folder and without the -properties Configuration=Release option nuget usually tries to find a dll in the Debug folder.
Running nuget pack manually gave me an useful error message. Running it as post build event I got the same obscure error message as you.

Categories

Resources