PowerShell
===
###### tags: `script` `powershell`
[TOC]
---
# 使用
win10自带。其他系统或其他版本的安装参考[官方文档](https://docs.microsoft.com/zh-cn/powershell/scripting/install/installing-powershell?view=powershell-7)。
## 控制台
`win`+`s`或`w`+`r`: powershell (推荐使用PowerShell ISE)
## ISE 集成脚本环境
`win`+`s`: powershell ise
`win`+`r`: powershell_ise
### 特点
- 允许多行编辑:提行`shift`+`enter`
- 允许选择运行:选中+`F5`
- 灵活的文本帮助(如自动补全)
# 核心命令句法
powershell命令主要分为4类:cmdlets, shell functions, scripts& native win32 executables。
## cmdlet
### 主要格式
**Verb-Object -Parameter Argument**
```python
PS> Get-ChilItem -Recurse -Filter p*.odt D:\ # 获取D:盘内各文件夹中p开头的.odt文件
```
- 查找命令是否存在`Get-Command`
- 查找命令使用方法`Get-Help`
### 特点
#### 1. 不区分大小写
#### 2. 支持别名使用
- 其他shell语言的部分命令也能直接使用,如cd,curl, del, dir, echo, find,pushd, set, sleep, start, timeout等。
```python
PS> dir d:\p*.odt # 直接使用cmd的dir命令
```
- 但是不是所有命令都能用,如call, exit, path, winget等。
- 查找别名是否可用及其在powershell中对应的cmdlet:**Get-Command [CommandName]**
```python
PS> Get-Command set # 查找set命令是否可用。若可用显示set所对应的标准cmdlet形式;若不可用,报错。
CommandType Name Version Source
----------- ---- ------- ------
Aliase set -> Set-Variable
```
- 自定义别名 `Set-Alias`
```python
PS> Set-Alias -Name list -Value Get-ChildItem # 自定义cmdlet的Get-ChildItem的别称为list
PS> Get-Command list
CommandType Name Version Source
----------- ---- ------- ------
Alias list -> Get-ChildItem
```
#### 3.支持缩写
- 如`Get-ChildItem`可缩写为`gci`。
- 查找缩写对应标准cmdlet `Get-Alias`
```python
PS> Get-Alias cls # 查找cls对应的标准cmdlet
CommandType Name Definition
----------- ---- ----------
Alias cls Clear-Host
```
- 查找cmdlet对应缩写 `Get-Alias -Definition [cmdlet]`
```python
PS> Get-Alias -Definition Clear-Host # 查找cls对应的标准cmdlet
CommandType Name Definition
----------- ---- ----------
Alias cls -> Clear-Host
cls -> clear
```
## script
**.ps1**文件
### 运行
- 运行权限:
直接运行.ps1可能会出现权限问题:设置[ExecutionPolicy](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7)接触限制
- 运行平台:
支持多种平台的运行,如console prompt可直接运行
以**console prompt**运行`test.ps1`为例
```python
PS> powershell -executionpolicy remotesigned -file test.ps1
```
# 基本语法...
## 类型
- 支持基于.NET的各种类型:int, single, double, char, string, bool, hashtable, array…
- 查看对象类型 `[object].GetType()`或`[object].GetType().FullName`
- 变量 `$[varName]`
- automatic variables: ps创建与维护的变量。 `$?`(存储最后一个命令的执行状态,布尔值),`$_`(当前对象),`$args`(传递的参数),`$Error`,`$true`,`$false`…
## 操作符
- 支持数学运算符、赋值操作符、格式操作符、比较操作符、逻辑运算符(大多用英文简写表示)

- 数学运算的整除.5时取最近偶数
- 转义符: `
- 注释:单行`# ... `;跨行`<# ... #>`
- `.`调用属性;`::`获取类的静态成员(属性或方法)
- `>`覆写文件内容;`>>`增加文件内容
- 模式匹配与文本调用:`-like`,`-match`,`-replace`,`-join`,`-split`
```python
PS> 'one' –like 'o*' # return $true
PS> 'Hello' –match '[jkl]' # return $true
PS> 'Hello' –replace 'ello','i' # return 'Hi'
PS> $in = 1,2,3; $out= -join $in; $out # return '123'
PS> 'a:b:c:d:e' -split ':' # return 'a''b''c''d'
```
- 字符串操作的大小写敏感设置:`-eq`,`-like`,`-match`,`-replace`,`-split`可设置大小写敏感。若设置为敏感,则给操作符加前缀c(如大小写敏感的相等`-ceq`);若不敏感,则加前缀为i(如大小写不敏感的匹配`-imatch`)
- 格式转换 `-as`
- 分组操作:返回形式为一个值`(...)`,返回一个值或多值构成的数组`$(...)`,返回数组`@(...)`
## 控制结构
- 常用条件、循环、选择结构:if, do, while, for, foreach, switch, continue, break, label

- 两个效率更高的控制cmdlet:`ForEach-Object`,`Where-Object`
```
PS> 30000, 56798, 12432 | ForEach-Object -Process {$_/1024}
PS> Get-Service | Where-Object {$_.Status -eq "Stopped"} # 等价于 Get-Service | where Status -eq "Stopped" #
```
## 函数
**function [FuncName] {[statementlist]}**
- 一般传参用`$args`
```python
PS> function hello { "Hello there $args, how are you?" }
PS> hello Bob # return "Hello there Bob, how are you?""
```
- 指定参数
**function [FuncName] ([ParameterList]) {[statementlist]}** 或 **function [FuncName] {param ([ParameterList]) [statementlist]}**
# 常用模块
官方文件 [Docs/Powershell/Scripting/Reference/](https://docs.microsoft.com/en-us/powershell/module/cimcmdlets/?view=powershell-5.1) 將powershell主要cmdlet按module分类介绍;[powershell實踐教材](https://1c-predpriyatie-qlik.ivan-shamaev.ru/wp-content/uploads/2018/01/Windows_PowerShell_in_Action_3rd_Edition.pdf)將主要cmdlet按实际使用的功能分类介绍。
这里主要采用官方文件的结构介绍部分cmdlet。
> *《 powershell实战 》基础章(一二三五六章)后感觉难度陡增,不了解脚本语言/计算机基础的话,有点难以理解。*
>
> *部分主要介绍一些基本的文件管理和系统设置方法(Core和Provider部分可能能取代.bat的作用, COM和WMI部分能能取代.vbs的作用)。*
## Core (施工中)
将以Object为依据,分类解释
- [Host](https://www.notion.so/Microsoft-PowerShell-Core-55c0ce7438874cbb8d7d517666579215)
# WorkFlow& Job (施工中)
# Debug, Error& Eception (施工中)
# 参考资料
- 教材:[powershell in action, 3rd edition](https://1c-predpriyatie-qlik.ivan-shamaev.ru/wp-content/uploads/2018/01/Windows_PowerShell_in_Action_3rd_Edition.pdf)
- 官方文档:[powershell documentation](https://docs.microsoft.com/en-us/powershell/)
- powershell实例:[TechNet Scripts](https://gallery.technet.microsoft.com/)
# 补充
1. 提到`@(...)`的位置:[官方文档](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-5.1#the-array-sub-expression-operator)和[powershell实战](https://livebook.manning.com/book/windows-powershell-in-action-third-edition/chapter-4/39)
2. 查看ps版本:`$PSVersionTable`
3. parameter 和 argument: parameter形式参数,argument实际参数
4. [其他分享资料和链接](https://hackmd.io/@D/ta/edit)