如何在 .csx 脚本中访问命令行参数
本文关键字:访问 命令行 参数 脚本 csx | 更新日期: 2023-09-27 17:58:17
我正在使用csi.exe
C#交互式编译器来运行.csx
脚本。如何访问提供给脚本的任何命令行参数?
csi script.csx 2000
如果您不熟悉 csi.exe,以下是使用消息:
>csi /?
Microsoft (R) Visual C# Interactive Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.
Usage: csi [option] ... [script-file.csx] [script-argument] ...
Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop).
CSI有一个Args
全局,可以为您解析参数。在大多数情况下,这将获得所需的参数,就像您在 C/C++ 程序中访问argv
或在 C# Main()
签名static void Main(string[] args)
中访问args
一样。
Args
有一种IList<string>
而不是string[]
。因此,您将使用 .Count
来查找参数的数量,而不是 .Length
。
下面是一些示例用法:
#!/usr/bin/env csi
Console.WriteLine($"There are {Args.Count} args: {string.Join(", ", Args.Select(arg => $"“{arg}”"))}");
还有一些示例调用:
ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx
There are 0 args:
ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx hi, these are args.
There are 4 args: “hi,”, “these”, “are”, “args.”
ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx 'hi, this is one arg.'
There are 1 args: “hi, this is one arg.”
这是我
的脚本:
var t = Environment.GetCommandLineArgs();
foreach (var i in t)
Console.WriteLine(i);
将参数传递给 csx:
scriptcs hello.csx -- arg1 arg2 argx
打印输出:
hello.csx
--
arg1
arg2
argx
键是 csx 和脚本参数之间的"--"。
Environment.GetCommandLineArgs()
返回该示例的["csi", "script.csx", "2000"]
。