/dotnet-script

Run C# scripts from the .NET CLI.

Primary LanguageC#MIT LicenseMIT

dotnet script

Run C# scripts from the .NET CLI.

Build status

Build server Platform Build status
AppVeyor Windows
Travis Linux/ OS X

Installing

Prerequisites

The only thing we need to install is .Net Core

Windows

choco install dotnet.script

We also provide a PowerShell script for installation.

(new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/filipw/dotnet-script/master/install/install.ps1") | iex

Linux and Mac

curl -s https://raw.githubusercontent.com/filipw/dotnet-script/master/install/install.sh | bash

If permission is denied we can try with sudo

curl -s https://raw.githubusercontent.com/filipw/dotnet-script/master/install/install.sh | sudo bash

Docker

A Dockerfile for running dotnet-script in a Linux container is available. Build:

cd build
docker build -t dotnet-script ..

And run:

docker run -it dotnet-script --version

Usage

Our typical helloworld.csx might look like this

#! "netcoreapp1.1"
#r "nuget:NetStandard.Library,1.6.1"

Console.WriteLine("Hello world!");

Let us take a quick look at what is going on here.

#! "netcoreapp1.1" tells OmniSharp to resolve metadata in the context of anetcoreapp1.1 application.

#r "nuget:NetStandard.Library,1.6.1" brings in the the NetStandard.Library 1.6.1 from NuGet.

That is all it takes and we can execute the script

dotnet script helloworld.csx

Scaffolding

Simply create a folder somewhere on your system and issue the following command.

dotnet script init

This will create Helloworld.csx along with the launch configuration needed to debug the script in VS Code.

.
├── .vscode
│   └── launch.json
├── helloworld.csx
└── omnisharp.json

Passing arguments to scripts

All arguments after -- are passed to the script in the following way:

dotnet script foo.csx -- arg1 arg2 arg3

Then you can access the arguments in the script context using the global Args collection:

foreach (var arg in Args)
{
    Console.WriteLine(arg);
}

All arguments before -- are processed by dotnet script. For example, the following command-line

dotnet script -d foo.csx -- -d

will pass the -d before -- to dotnet script and enable the debug mode whereas the -d after -- is passed to script for its own interpretation of the argument.

NuGet Packages

dotnet script has built-in support for referencing NuGet packages directly from within the script.

#r "nuget: AutoMapper, 9.1.0"

package

Note: Omnisharp needs to be restarted after adding a new package reference

Debugging

The days of debugging scripts using Console.WriteLine are over. One major feature of dotnet script is the ability to debug scripts directly in VS Code. Just set a breakpoint anywhere in your script file(s) and hit F5(start debugging)

debug