Skip to content

CS Script Command Line Interface

oleg.shilo edited this page Oct 11, 2021 · 20 revisions
Since porting CS-Script on .NET 5 the documentation is still in the process of being refined and cleared from the legacy content.
Thus it may contain some minor inaccuracies until both statuses below are set to full and complete or this disclaimer is removed.
.NET 5 accuracy status: partial
Review/update status: pending

CS-Script - Command Line Interface

As many other tools CS-Script provides an intensive command line interface that can be used from shell/terminal (e.g. Bash, PowerShell, command-prompt). This interface is particularly useful fo environments like Linux, where working from terminal is a predominate development approach.

CLI Commands

Usage: cscs <switch 1> <switch 2> <file> [params] [//x]

<switch 1>

--help|-help|-? [<command>|<scope[:md]>]

Displays either generic or command specific help info.

   <command> - one of the supported CLI commands
   <scope>    
         `cli`    - print documentation for all CLI commands
         `syntax` - print the complete documentation for scripting syntax
         `md`     - print the documentation in GitHub markdown format
         (e.g. `-help cli:md`)

Reversed order of parameters for the command specific help is also acceptable. The all following argument combinations print the same help topic for 'cache' command:

   -help cache
   -? cache
   -cache help
   -cache ?

-e

Compiles script into console application executable.


-ew

Compiles script into Windows application executable.


-c[:<0|1>]

Executes compiled script cache (e.g. /script.cs.dll) if found. This command improves performance by avoiding compiling the script if it was not changed since last execution.

   -c:1|-c  - enable caching
   -c:0     - disable caching (which might be enabled globally)

-ca

Compiles script file into cache file (e.g. /script.cs.dll).


-cd

Compiles script file into assembly (.dll) in the script folder without execution.


-check

Checks script for errors without execution.


-proj

Shows script 'project info' - script and all its dependencies.


-vs

Generates .NET project file and opens it in Visual Studio. The path to the Visual Studio executable (devenv.exe) needs to be defined in the environment variable CSSCRIPT_VSEXE.


-vscode

Generates .NET project file and opens it in Visual Studio Code. The path to the Visual Studio Code executable (code.exe) needs to be defined in the environment variable CSSCRIPT_VSCODEEXE.


-cache[:<ls|trim|clear>]

Performs script cache operations.

 ls    - lists all cache items.
 trim  - removes all abandoned cache items.
 clear - removes all cache items.

-co:<options>

Passes compiler options directly to the language compiler. (e.g. -co:/d:TRACE pass /d:TRACE option to C# compiler or -co:/platform:x86 to produce Win32 executable)


-ng|-engine:<csc:dotnet>]

Forces compilation to be done by one of the supported .NET engines.

dotnet - dotnet.exe compiler; this is the most versatile compilation engine though it does have a startup overhead when running the script for the first time. It requires .NET SDK to be installed on the target system.

csc - csc.exe compiler; the fastest compiler available. It is not suitablefor WPF scripts as csc.exe cannot compile XAML. The compilation is performed in the separate child process build.exe which is somewhat equivalent of VBCSCompiler.exe (build server) from .NET toolset. It requires .NET SDK to be installed on the target system. CS-Script communicates with build.exe build server via socket (default port 17001). You can control port value via environment variable 'CSS_BUILDSERVER_CSC_PORT' Value csc-inproc will suppress spinning off an build server process and .NET csc.exe will be called directly instead. This option convenient when socket communication is undesirable for whatever reason. Though in this case all the performance benefits of -ng:csc will be lost and then you are better off using -ng:dotnet instead.

roslyn - Microsoft.CodeAnalysis.CSharp.Scripting.dll compiler; this is the most portable compilation engine. It does not require .NET SDK being installed. Though it does have limitations (see documentation). The compilation is performed in the separate child process cscs (another instance of script engine) which is somewhat equivalent of VBCSCompiler.exe (build server) from .NET toolset. CS-Script communicates with cscs build server via socket (default port 17002). You can control port value via environment variable 'CSS_BUILDSERVER_ROSLYN_PORT' Value roslyn-inproc will suppress spinning off an external process and Roslyn compiler will be hosted in the original process of script engine instead. This option convenient when socket communication is undesirable for whatever reason. Though in this case performance will be affected on the first run of the script.

(e.g. cscs -engine:dotnet sample.cs
      cscs -ng:csc sample.cs)
      cscs -ng:roslyn-inproc sample.cs)
      cscs -ng:roslyn sample.cs)

-s|-sample[:<C# version>]

-s:7 - prints C# 7+ sample. Otherwise it prints the default canonical 'Hello World' sample. (e.g. cscs -s:7 > sample.cs).


-new[:<type>] [<script name>]

Creates a new script. Usage: -new[:] [] type - script template based on available types. output - location to place the generated script file(s).

Type           Template
---------------------------------------------------
console         Console script application (Default)
console-vb      Console VB script application
winform         Windows Forms (WinForms) script application
winform-vb      Windows Forms (WinForms) VB script application
wpf             WPF script application
wpf-cm          Caliburn.Micro based WPF script application
toplevel|top    Top-level class script application with no entry point
                (available on C# 9 only)
 
Legacy templates:
auto            Auto-class (classless) script application; use 'toplevel' instead
freestyle       Free style (no entry point) script application; use 'toplevel' instead
 
Examples:
    cscs -new script
    cscs -new:toplevel script.cs
    cscs -new:console console.cs
    cscs -new:winform myapp.cs
    cscs -new:wpf hello

-code[:show] <script code>

Executes script code directly without using a script file. Sample:

cscs -code "Console.WriteLine(Environment.UserDomainName);#nConsole.WriteLine(#''%USERNAME%#'');"
cscs -code "using System.Linq;#nSystem.Diagnostics.Process.GetProcessesByName(''notepad'').ToList().ForEach(x => x.Kill());"
cscs -code "SetEnvironmentVariable(`ntp`,`notepad.exe`, EnvironmentVariableTarget.Machine)"

The -code argument must be the last argument in the command. The only argument that is allowed after the <script code> is //x

Escaping special characters sometimes can be problematic as many shells have their own techniques (e.g. PowerShell collapses two single quote characters) that may conflict with CS-Script escaping approach.This is the reason why CS-Script offers multiple escape techniques. It can be beneficial during the troubleshooting to use -code:show command that outputs the received CLI arguments and the interpreted C# code without the execution.

Since command line interface does not allow some special characters they need to be escaped.

Escaped         Interpreted character
-------------------------------------
#n        ->    <\n>
#r        ->    <\r>
#''       ->    "   
''        ->    "   
#``       ->    "   
`n        ->    <\n>
`r        ->    <\r>
``        ->    "   

-wait[:prompt]

Waits for user input after the execution before exiting. If specified the execution will proceed with exit only after any std input is received. Applicable for console mode only. prompt - if none specified 'Press any key to continue...' will be used


-ac|-autoclass[:<0|1|2|out>]

Legacy command: executes scripts without class definition. Use top-level statements (C# 9) scripts instead.

 -ac     - enables auto-class decoration (which might be disabled globally).
 -ac:0   - disables auto-class decoration (which might be enabled globally).
 -ac:1   - same as '-ac'
 -ac:2   - same as '-ac:1' and '-ac'
 -ac:out - prints auto-class decoration for a given script file. The argument must be followed by the path to script file.

Automatically generates 'static entry point' class if the script doesn't define any.

    using System;
 
    void Main()
    {
        Console.WriteLine("Hello World!";
    }
 

Using an alternative 'instance entry point' is even more convenient (and reliable). The acceptable 'instance entry point' signatures are:

void main()
void main(string[] args)
int main()
int main(string[] args)

Note, having any active code above entry point is acceptable though it complicates the troubleshooting if such a code contains errors. (see https://github.com/oleg-shilo/cs-script/wiki/CLI---User-Guide#command-auto-class)

By default CS-Script decorates the script by adding a class declaration statement to the start of the script routine and a class closing bracket to the end. This may have an unintended effect as any class declared in the script becomes a 'nested class'. While it is acceptable for practically all use-cases it may be undesired for just a few scenarios. For example, any class containing method extensions must be a top level static class, what conflicts with the auto-class decoration algorithm.

The solution to this problem is to allow some user code to be protected from being included into the decorated code. User can achieve this by placing '//css_ac_end' statement into the code. Any user code below this statement will be excluded from the decoration and stay unchanged.


<switch 2>

-dbg|-d

Forces compiler to include debug information.

-l[:<0|1>]

'local' (makes the script directory a 'current directory'). '1' is a default value.

-v|-ver|--version

Prints CS-Script version information.

-dbgprint[:<0:1>]

Controls whether to enable Python-like print methods (e.g. dbg.print(DateTime.Now)). This setting allows controlling dynamic referencing of script engine assembly containing implementation of Python-like print methods dbg.print and derived extension methods object.print() and object.dup(). While dbg.print is extremely useful it can and lead to some referencing challenges when the script being executed is referencing assemblies compiled with dbg.print already included. The simplest way to solve this problem is disable the dbg.cs inclusion.

 -dbgprint:1   enable `dbg.cs` inclusion; Same as `-dbgprint`;
 -dbgprint:0   disable `dbg.cs` inclusion;

-verbose

Prints runtime information during the script execution. '-verbose2' additionally echoes compiling engine (e.g. csc.dll) input and output. (applicable for console clients only)

-profile

Prints script loading performance information during the script execution.

-speed

Prints script initialization/compilation time information of the .NET compiler. It is a convenient way of testing performance of the .NET distribution.

-server[:<start|stop|restart|add|remove|ping>]

Prints the information about build server. Note, the server starts automatically on the script execution that is configured to use the 'csc' or 'roslyn' engine. Build server is a background process which implements hop loading of C# compiler csc.exe. Somewhat similar to VBCSCompiler.exe. This option is only relevant if compiler engine is set to 'csc' (see '-engine' command).

 -server:start   - deploys and starts build server. Useful if you want to start the server on system startup.
 -server:stop    - stops starts build server
 -server:restart - restarts build server
 -server:reset   - stops, re-deploys and starts build server
 -server:add     - deploys build server
 -server:remove  - removes build server files. Useful for troubleshooting.
 -server:ping    - Pins running instance (if any) of the build server

This option is only relevant if compiler engine is set to 'roslyn' (see '-engine' command). Roslyn based build server variant is much simpler so it only exposes start and stop interface.

 -server_r:start - deploys and starts Roslyn build server
 -server_r:stop  - stops starts Roslyn build server

-tc

Trace compiler input produced by CS-Script code provider CSSRoslynProvider.dll. It's useful when troubleshooting custom compilers (e.g. Roslyn on Linux).

-wpf[:<enable|disable|1|0>]

Enables/disables WPF support on Windows by updating the framework name in the *.runtimeconfig.json file

 -wpf               - prints current enabled status
 -wpf:<enable|1>    - enables WPF support
 -wpf:<disable|0>   - disables WPF support

-config[:<option>]

Performs various CS-Script config operations

 -config:none               - ignores config file (uses default settings)
 -config:create             - creates config file with default settings
 -config:default            - prints default config file
 -config:<raw|xml>          - prints current config file content
 -config[:ls]               - lists/prints current config values
 -config:get:name           - prints current config value
 -config:set:name=value     - sets current config value
 -config:set:name=add:value - updates the current config value content by appending the specified value.
 -config:set:name=del:value - updates the current config value content by removing all occurrences of the specified value.
 -config:<file>             - uses custom config file

Note: The property name in -config:set and -config:set is case insensitive and can also contain '_' as a token separator that is ignored during property lookup.

(e.g. cscs -config:none sample.cs
      cscs -config:default > css_VB.xml
      cscs -config:set:DefaultCompilerEngine=dotnet
      cscs -config:set:DefaultArguments=add:-ac
      cscs -config:set:default_arguments=del:-ac
      cscs -config:c:\cs-script\css_VB.xml sample.vb)

-out[:<file>]

Forces the script to be compiled into a specific location. Used only for very fine hosting tuning. (e.g. cscs -out:%temp%%pid%\sample.dll sample.cs

-r:<assembly 1>,<assembly N>

Uses explicitly referenced assembly. It is required only for rare cases when namespace cannot be resolved into assembly. (e.g. cscs /r:myLib.dll myScript.cs).

-dir:<directory 1>,<directory N>

Adds path(s) to the assembly probing directory list. You can use a reserved word 'show' as a directory name to print the configured probing directories. (e.g. cscs -dir:C:\MyLibraries myScript.cs; cscs -dir:show).

-precompiler[:<file 1>,<file N>]

Specifies custom precompiler. This can be either script or assembly file. Alias - pc[:<file 1>,] If no file(s) specified prints the code template for the custom precompiler. The spacial value 'print' has the same effect (e.g. cscs -pc:print). There is a special reserved word 'nodefault' to be used as a file name. It instructs script engine to prevent loading any built-in precompilers like the one for removing shebang before the execution. (see https://www.cs-script.net/cs-script/help-legacy/precompilers.html)

-pvdr|-provider:<file>

Location of the alternative/custom code provider assembly. Alias - pvdr: If set it forces script engine to use an alternative code compiler.

C#7 support is implemented via Roslyn based provider: '-pvdr:CSSRoslynProvider.dll'.If the switch is not specified CSSRoslynProvider.dll file will be use as a code provider if it is found in the same folder where the script engine is. Automatic CSSRoslynProvider.dll loading can be disabled with special 'none' argument: -pvdr:none. (see https://www.cs-script.net/cs-script/help-legacy/help/non_cs_compilers.html)

-nuget[:<package|purge>]

Installs new or updates existing NuGet package. This command allows light management of the NuGet packages in the CS-Script local package repository (%PROGRAMDATA%\CS-Script\nuget). The tasks are limited to installing, updating and listing the local packages.

 -nuget           - prints the list of all root packages in the repository
 -nuget:<package> - downloads and installs the latest version of the package(s). 
                    Wild cards can be used to update multiple packages. For example '-nuget:ServiceStack*' will update all already installed ServiceStack packages.
                    You can also use the index of the package instead of its full name.

Installing packages this way is an alternative to have '//css_nuget -force ...' directive in the script code as it may be more convenient for the user to update packages manually instead of having them updated on every script execution/recompilation.

-syntax

Prints documentation for CS-Script specific C# syntax.

-commands|-cmd

Prints list of supported commands (arguments).