powershell_配置文件与脚本编写(字符串插值/运算符与表达式/函数参数/控制流)(by offical documents:learn)/实现head.ps1脚本


link
在这里插入图片描述
在这里插入图片描述

获取对象属性

<object> | select-object *
例如
$Profile | Select-Object *

插值

双引号中可以插值

简单值:

$<expression>

较复杂值:

$(<complex expression>)
插值可以嵌套!

插值eg.

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语句高级条件的时候,比较有用

猜你喜欢

转载自blog.csdn.net/xuchaoxin1375/article/details/121205537