关于PowerShell命令的一些基本知识

PowerShell的命令叫做cmdlet

具有一致的命名规范,都采用动词-名词形式,如New-Item

动词部分一般为Add、New、Get、Remove、Set等

命令的别名一般兼容Windows Command以及Linux Shell,如Get-ChildItem命令使用dir或ls均可

PowerShell 命令产生的结果都是DLR对象

PowerShell命令不区分大小写

以文件操作为例讲解PowerShell命令的基本用法

新建目录 New-Item b2 -ItemType Directory

新建文件 New-Item a.txt -ItemType File

删除目录 Remove-Item b2

递归列pre开头的文件或目录,只列出名称 Get-ChildItem -Recurse -Name -Filter "pre*“

显示文本内容 Get-Content a.txt

设置文本内容 Set-Content a.txt -Value "content1“

追加内容 Add-Content a.txt -Value “content2“

清除内容 Clear-Content a.txt

使用帮助

使用CHM查看帮助:在任务栏PowerShell图标上点右键即可

p_w_picpath

Get-Help命令(man/help),默认为精简,如果要查看全帮助,可使用 –Full 参数

例:查找关于Content的帮助 Get-Help Content

获取cmdlet命令

使用Get-Command(gcm)

获取Connent相关命令 gcm *Content*

别名(Alias)

显示所有命令的别名gal(Get-Alias)

新建别名 New-Alias tt Get-ChildItem

设置别名Set-Alias ls1 Get-ChildItem

导出别名列表 Export-Alias -Path alias.txt

导入别名列表 Import-Alias -Path alias.txt

格式化输出

Format-Wide eg: ls | Format-Wide

p_w_picpath

Format-List :以Key:Value形式展现

Format-Table:以列表展现

Format-Custom:以对象的层次关系展现

管道处理

循环处理 ls -Name | foreach {$_+"dsf"}

筛选 ls | where {$_ -match “admin”}

排序 ls | Sort-Object -Descending -Property length -Unique

选择 ls | Select-Object -Skip 10 -First 10