Skip to content

CS Script Command Line Interface

Oleg Shilo edited this page Jan 11, 2025 · 20 revisions

Like with 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 for environments like Linux, where working from terminal is a predominant development approach.

This document is auto-generated with the command css -help cli:md.

CLI Commands

Usage: cscs <switch 1> <switch 2> <file> [params] [//x]
  • file Specifies name of a script file to be run.
  • params Specifies optional parameters for a script file to be run.
  • //x Launch debugger just before starting the script.

<switch 1>

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

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`)
   <file>    - output file for the help content

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. Note this switch will force the use of dotnet compiler as csc is not capable of building executable assemblies. Thus //css_engine and -engine options will always be ignored.


-ew

Compiles script into Windows application executable (applicable only on Windows). Note this switch will force the use of dotnet compiler as csc is not capable of building executable assemblies. Thus //css_engine and -engine options will always be ignored.


-rx

Run script as an external process. This option is incompatible with VB scripts. This mode allows execution of the scripts that are otherwise incompatible with the runtime of the script engine (e.g. x86 vs x64, .NETCore vs .NETFramework). Note, this execution mode comes with some limitations (depending on the compilation engine):

  • csc The compiled script is executed with dotnet.exe launcher (e.g. dotnet script.dll).
  • dotnet The compiled script is executed directly as exe(e.g. script.exe).
  • roslyn This mode is not supported as Roslyn scripts do not support static main.

-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. An internal-use version of this command '-proj:csproj' can be also useful for troubleshooting.


-vs <script>|-vs:init [index_of_detected_VS_executable]

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. You can let CS-Script to detect installed Visual Studio executable and interactively select the detected executable for integrating it with CS-Script by using -vs:init option. Alternatively, you can even ask to integrate the first detected executable with: cscs -vs:init 0


-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. csc.exe or dotnet.exe). Note, some compiler options may not be compatible if they are passed to the wrong compiler executable (see compiler documentation). Though the fundamental switches like /platform:* are converted by CS-Script into compatible version between csc.exe and dotnet.exe. (e.g. -co:/d:TRACE pass /d:TRACE option to C# compiler or -co:/platform:x86 to produce Win32 executable)


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

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 suitable for WPF scripts as csc.exe cannot compile XAML. The compilation is performed in the separate child process build.exe which is somewhat equivalent to 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 the 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 the 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 is convenient when socket communication is undesirable for whatever reason. Though in this case performance will be effected 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
toplevel-x      Top-level class script application with no entry point; an advanced CS-Script integration samples.
cmd             Custom command script. See https://github.com/oleg-shilo/cs-script/wiki/Custom-Commands.

Legacy templates:
auto            Auto-class (classless) script application; use 'toplevel' instead
freestyle       Freestyle (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
    cscs -new:cmd edit

-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, which conflicts with the auto-class decoration algorithm.

The solution to this problem is to allow some user code to be protected from being included in the decorated code. Users 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 [output file]

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 the 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 to 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. You can use -ng option () It is a convenient way of testing performance of the .NET distribution.

-install/-uninstall

Sets/unsets CSSCRIPT_ROOT environment variable to the location of the script engine being executed. This environment variable is required for integration of CS-Script with Notepad++,Sublime Text and some other editors, which require CS-Script installed on the host OS. This command is only supported on Windows

-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 top loading of C# compiler csc.exe. Somewhat similar to VBCSCompiler.exe. These options are only relevant if the compiler engine is set to 'csc' or roslyn (see '-engine' command). Note, the build server is deployed on the first execution of the script with csc or roslyn engine. Though on Linux it has to be an execution with root privileges. Or you can just run sudo css -server:add.

 -server:start   - deploys and starts build server. Useful if you want to start the server on system startup.
 -server:stop    - stops 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

The following options are only relevant if the 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 Roslyn build server

And this is how you can start and stop both Roslyn and csc build servers with a single command:

 -servers:start - deploys and starts both Roslyn and csc build server
 -servers:stop  - stops both Roslyn and csc build server
 -kill          - a complete equivalent of -servers:stop

-netfx

Compile and execute the script on the latest .NET Framework compiler (csc.exe) found on the system. The script will be automatically executed as an external process thus the value of the -rx switchwill be ignored.

-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:<name> ?               - prints help for the configuration value specified by name
 -config:get:<name>             - prints current config value
 -config::<name>                - the same as `-config:get:name`
 -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 the 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 special 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 a special 'none' argument: -pvdr:none. (see https://www.cs-script.net/cs-script/help-legacy/help/non_cs_compilers.html)

-nuget[:restore]

Installs new or updates existing NuGet packages. It is a very close equivalent of dotnet restore command

 -nuget         - prints the list of all root packages in the repository
 -nuget:restore - Downloads and installs all packages specified in the script without executing the script. Effectively it is an equivalent of -check but with the forced nuget packages restore operation.
                  Using this option is an alternative to having '//css_nuget -force ...' directive in the script code as it may be a more convenient way of updating packages manually instead of having them updated on every script execution/recompilation.
                  You can set CSS_RESTORE_DONOT_CLEAN environment variable to disable removing temporary folders created during restore operations. This can be useful for troubleshooting NuGet packages restoring.```
---------------------------------------------
Note: A the current NuGet support model is available since v4.7.0. The old options of this `-nuget` command that are only available with the legacy NuGet support algorithm. This mode can be enabled by setting `LegacyNugetSupport` option to false: `css -config:set:LegacyNugetSupport=true`. Read more: https://github.com/oleg-shilo/cs-script/wiki/NuGet-Support

Legacy CLI:

-nuget[:<package|restore>]
This command allows a lightweight management of the NuGet packages. The functionality is limited to installing, restoring and updating the packages.

-nuget - prints the list of all root packages in the repository -nuget: - 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. (Not available with new NuGet support) -nuget:restore - Downloads and installs all packages specified in the script without executing the script.


### `-syntax`
Prints documentation for CS-Script specific C# syntax.

### `-commands|-cmd`
Prints list of supported commands (arguments) as well as the custom commands defined by user.

### `-list|-ls [<kill|k> | <kill-all|ka>`
Prints list of all currently running scripts.
If script execution tracking is undesirable you can disable it by setting DisableCSScriptProcessTracking environment variable to a non empty value.
 kill|k      - Allow user to select and user to select and terminate any running script.
 *           - Terminate all running scripts when 'kill' option is used.
               (e.g. cscs -list kill * ).


Clone this wiki locally