文章目录
- 获取对象属性
- 插值
- 简单值:
- 简单插值示例
- 较复杂值:
- 复杂插值eg1.
- 引用对象成员的插值示例
- 参数
- 参数声明(basic)
- 分配类型:
- 参数说明(with `parameter[]`)
- head.ps1
- 控制流
- overview
- operators
- overview:
- 表达式
link
获取对象属性
<object> | select-object *
例如
$Profile | Select-Object *
插值
在双引号中可以插值
简单值:
$<expression>
简单插值示例
较复杂值:
通用方式
$(<complex expression>)
插值可以嵌套!
复杂插值eg1.
Write-Host "Created backup at $( $DestinationPath + 'backup-' + $date).zip"
单引号无法插值!
- 示例2:获取当前目录下存在的符号链接
function getLinks {
param (
)
$step = (Get-ChildItem | Sort-Object -Property target -Descending | Select-Object name, linktype, target | Where-Object target -ne "")
Write-Output $step "-------------"
Write-Output "itemsCount: $($step.count)"
}
引用对象成员的插值示例
参数
分为脚本参数和函数参数
编写规则大致相同,但是在使用的时候需要注意,函数需要导入(或者说,导入函数所在的模块)
相关文档可以参考模块与脚本部分(而不仅仅时函数编写部分)
参数声明(basic)
param(
# your parameter list
)
分配类型:
分配类型。 例如,如果为参数分配类型,你可以指定该参数只接受字符串,而不接受布尔值。 这样,用户就知道了期望结果。 可以在参数前面加上类型(用括号括住),为该参数分配类型:
Param(
# the parameter has been set the default parameters
[string]$Path = './app',
[string]$DestinationPath = './'
)
参数说明(with parameter[]
)
实验环境不同,效果可能也不同(在vscode中的powershell插件控制下的PowerShell Integrated Console (v2021.10.2) 就无法使用!?
提示`
以下是powerhsell7.1中的结果
test code:
<# the more effective and popular method is to use the parameter[] #>
Param(
# to show the helpMessage tips,just type `!?`
# Mandatory=$true is optional.
[Parameter(Mandatory=$true,HelpMessage = "input your valid path(for demonstrate,I will just output to show the path.")]
# [Parameter(Mandatory, HelpMessage = "Please provide a valid path")]
$path
)
# the logic of your script,in the script ,I just use it to out put a sentence
Write-Output $path
head.ps1
param(
[int]$lines=5,
[parameter(mandatory, HelpMessage = "input a valid fileName")]
$fileName
)
Get-Content $fileName | Select-Object -First $lines
控制流
overview
流控制 - Learn | Microsoft Docs
operators
所有运算符 - PowerShell | Microsoft Docs
overview:
- 简短说明
- 长说明
- 算术运算符
- 赋值运算符
- 比较运算符
- 逻辑运算符
- 重定向运算符
- 拆分运算符和联接运算符
- 类型运算符
- 一元运算符
- 特殊运算符
表达式
这是重要的一块内容,在编写where
语句高级条件的时候,比较有用
- 7.1 Primary expressions
- 7.2 Unary operators
- 7.3 Binary comma operator
- 7.4 Range operator
- 7.5 Format operator
- 7.6 Multiplicative operators
- 7.7 Additive operators
- 7.8 Comparison operators
- 7.9 Bitwise operators
- 7.10 Logical operators
- 7.11 Assignment operators
- 7.12 Redirection operators