Powershell 的基础使用III 本质是 dotNet

Powershell 的基础使用III 本质是 dotNet

前言

这里是相关基础知识的语言基础篇.

.Net 运行时

pwsh 依赖于 .Net 的运行时, 安装时便携带了基础的运行时, 使用以下指令获得运行时版本: [System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription 或旧版本 [System.Runtime.InteropServices.RuntimeEnvironment]::GetSystemVersion()

比如 Windows 自带的 v1 版本只能用第二种方式, 如输出 v4.0.30319 只能使用 .net4 的运行时, v7.4 则捆版了 v8.0.4 的运行时, 相应的, 可以使用对应的 .dotnet8 api 或者对应的 .dotnet standard-2.0 api

用例1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using namespace System.Text.Json

class Bus {
[int]$len
[int]$size
}


[System.Text.RegularExpressions.Regex]::Replace('football"`GO','["`]',"_")
$ops = [JsonSerializerOptions]::new();
$ops.MakeReadOnly($true)
"`$ops.IsReadOnly: $($ops.IsReadOnly)"
[Bus]$bus = [Bus]::new()
$bus.size = 3
$bus.len = 13
$json = [JsonSerializer]::Serialize($bus, $ops);
[JsonSerializer]::Deserialize($json, [Bus], $ops)

一些小结

  • 像开发 C# 一样,可以引用 namespace
  • [Bus] 等效于 typeof(Bus)
  • [int] 本质等效于 [System.UInt32] , 更多的参见类型加速器