Reputation: 871
I'm trying to create a basic PowerShell Module with a binary Cmdlet internals, cause writing things in PowerShell only doesn't look as convenient as in C#.
Following this guide, it looks like I have to:
project.json
RootModule
, targeting my .dll
.dll
nearby manifestPSModulePath
but, when I'm trying to Import-Module
, PowerShell core complains on missing runtime:
Import-Module : Could not load file or assembly 'System.Runtime, Version=4.1.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system
cannot find the file specified.
At line:1 char:1
Am I doing something wrong, or such tricky things are not supported yet as well?
Upvotes: 19
Views: 8182
Reputation: 11032
For netcore, there is a new template for powershell that you can install and use then you can modify the c# code.
$ dotnet new -i Microsoft.PowerShell.Standard.Module.Template
$ dotnet new psmodule
dotnet build
For more details read doc
Upvotes: 5
Reputation: 201632
This gets a lot easier with .NET Core 2.0 SDK
and Visual Studio 2017 Update 15.3
(or higher). If you don't have VS, you can do this from the command line with the .NET Core 2.0 SDK.
The important bit is to add the PowerShellStandard.Library 3.0.0-preview-01
(or higher) NuGet package to your project file (.csproj).
Here is a simple command line example:
cd $home
dotnet new classlib --name psmodule
cd .\psmodule
dotnet add package PowerShellStandard.Library --version 3.0.0-preview-01
Remove-Item .\Class1.cs
@'
using System.Management.Automation;
namespace PSCmdletExample
{
[Cmdlet("Get", "Foo")]
public class GetFooCommand : PSCmdlet
{
[Parameter]
public string Name { get; set; } = string.Empty;
protected override void EndProcessing()
{
this.WriteObject("Foo is " + this.Name);
base.EndProcessing();
}
}
}
'@ | Out-File GetFooCommand.cs -Encoding UTF8
dotnet build
cd .\bin\Debug\netstandard2.0\
ipmo .\psmodule.dll
get-foo
To get this same command to run in Windows PowerShell 5.1 requires a bit more work. You have to execute the following before the command will work:
Add-Type -Path "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.netcore.app\2.0.0\ref\netcoreapp2.0\netstandard.dll"
Upvotes: 14
Reputation: 2413
You need to use PowerShell Core
to write a PowerShell CmdLet in .NET Core.
There is a guide here, including corrections to your project.json
:
https://github.com/PowerShell/PowerShell/tree/master/docs/cmdlet-example
To summarize you need the following in your project.json
"dependencies": {
"Microsoft.PowerShell.5.ReferenceAssemblies": "1.0.0-*"
},
"frameworks": {
"netstandard1.3": {
"imports": [ "net40" ],
"dependencies": {
"Microsoft.NETCore": "5.0.1-*",
"Microsoft.NETCore.Portable.Compatibility": "1.0.1-*"
}
}
}
Upvotes: 1