[Powershell] Powershell简明教程

Visual Studio Code搭建Powershell环境

  1. 下载并安装Visual Studio Code。
    https://code.visualstudio.com/

  2. 安装powershell扩展。
    width=200px

  3. 关闭,重新打开Visual Studio Code。

  4. 新建文件并另存为Powershell扩展名。系统自动加载Powershell插件来进行编译。
    上面代码区,使用F5编译执行; 下面是交互模式。

Powershell模块

服务器添加角色的时候,对应的Powershell Module也一并安装。

默认的模块存放位置: C:\Windows\system32\windowspowershell\v1.0\modules

一个module包含:

  • Command Let
  • Alias
  • Function
  • Application

使用module的流程:获取Module -> 安装Module -> 使用Module中的命令

查看当前加载的Module

get-module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Manifest   1.0.0.0    NetTCPIP                            {Find-NetRoute, Get-NetCompartment, Get-NetIPAddress, Get-...
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...

查看命令所属于的Module

get-command get-alias | ft name, commandtype, module

Name      CommandType Module
----      ----------- ------
Get-Alias      Cmdlet Microsoft.PowerShell.Utility

Powershell会随着运行命令,而自动加载命令所属的模块。

查看系统中所有可用的Module

get-module -ListAvailable

    目录: C:\Program Files\WindowsPowerShell\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.1.1      HackSql
*忽略中间部分*
Manifest   2.1.0.0    xMySql                              {Get-ArchitectureName, Get-MySqlExe, Get-ShortVersion, Get...


    目录: C:\Windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0.0.0    AppBackgroundTask                   {Disable-AppBackgroundTaskDiagnosticLog, Enable-AppBackgro...
*忽略中间部分*
Manifest   1.0.0.0    WindowsUpdate                       Get-WindowsUpdateLog

从Powershell Gallery中查找Module

Find-Module -name *qrcode*

Version    Name                                Repository           Description
-------    ----                                ----------           -----------
2.6.0      QRCodeGenerator                     PSGallery            creates QR codes offline
1.2.0.80   QrCodes                             PSGallery            PowerShell module that uses the Google ZXing.Net library to generate QRCodes.
1.0.1      QRCodeSt                            PSGallery            Automatically Creates QR codes as PNG images filled with whatever info you want. Works on all PowerShell versions and editions 
'''

从Powershell Gallery中安装Module
···
Find-Module -name QRcodeGenerator  |Save-Module -Path C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

获取一个Module中的命令

Get-Command -Module QRCodeGenerator -noun QR*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           New-QRCodeGeolocation                              2.6.0      QRCodeGenerator
Alias           New-QRCodeText                                     2.6.0      QRCodeGenerator
Alias           New-QRCodeTwitter                                  2.6.0      QRCodeGenerator

Powershell命令

Powershell命令的形式
Powershell命令的格式是Verb-Noun的形式存在。

Powershell命令的帮助
Get-Command -module -verb -noun命令获取命令的名称。
Get-Help 命令查看命令的帮助。
Update-Help更新命令的帮助文件。

命令帮助的解释
Get-Process [[-Name] <System.String[]>] [-ComputerName <System.String[]>] [-FileVersionInfo] [-Module] []

  • 参数两边的中括号,代表这个参数是可选的。
  • [-name] <System.String[]>中, [-name]代表参数名称可以省略,所以就是位置参数。 <System.String[]>是字符串数组。

Powershell的别名
Alias的目的为了符合管理员的操作习惯或者向后兼容。

Get-Alias获取系统中的所有别名。

get-alias

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           Add-AppProvisionedPackage                          3.0        Dism
Alias           Add-ProvisionedAppPackage                          3.0        Dism

Get-Alias 别名 显示出别名的详细信息

Get-Alias cat | fl


DisplayName       : cat -> Get-Content
CommandType       : Alias
Definition        : Get-Content
ReferencedCommand : Get-Content
ResolvedCommand   : Get-Content

Powershell Provider

Powershell所支持的层次化结构数据,例如:文件系统,注册表、证书服务。 都是建立在powershell的provider之上的。

导入模块Import-Module的时候,也可能会添加新的PSProvider,例如ActiveDirectory模块。

Get-PSProvider 查看系统所支持的Provider。

Get-PSProvider

Name                 Capabilities                                      Drives
----                 ------------                                      ------
Registry             ShouldProcess, Transactions                       {HKLM, HKCU}
Alias                ShouldProcess                                     {Alias}
Environment          ShouldProcess                                     {Env}
FileSystem           Filter, ShouldProcess, Credentials                {C, D, E}
Function             ShouldProcess                                     {Function}
Variable             ShouldProcess                                     {Variable}

Get-PSDrive 查看PSProvider所提供的结构化目录。

Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root                                              
----           ---------     --------- --------      ----                                               
Alias                                  Alias
C                 180.90         19.10 FileSystem    C:\
Cert                                   Certificate   \
D                 218.18         57.51 FileSystem    D:\
E                   0.87         28.85 FileSystem    E:\
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan

Powershell的变量

Powershell定义的变量,会临时存储到PSProvider的Variable中。

Powershell的对象

对象的属性类型:

  • Property: dotnet定义对象的原生属性。
  • AliasProperty: dotnet定义对象属性的别名。
  • ScriptProperty:通过执行一些脚本来获取信息。

对象的方法:
可以在微软的dotnet中类的说明中查看帮助。

Powershell与对象操作相关的命令

Powershell导出内容

out系命令

get-command -Module Microsoft.Powershell.* -verb out

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Out-Default                                        3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Out-File                                           3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Out-GridView                                       3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Out-Host                                           3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Out-Null                                           3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Out-Printer                                        3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Out-String                                         3.1.0.0    Microsoft.PowerShell.Utility

Out-Host: 将内容直接输出到屏幕上。所有命令执行的时候,都是默认将命令Pipeline到out-host的InputObject参数。
Out-host的Paging开关参数可以让输出进行分页和分行显示。

Out-host -InputObject (Get-Service) -Paging

Status   Name               DisplayName
------   ----               -----------
Running  AarSvc_1b4f241     Agent Activation Runtime_1b4f241
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Monitor Service

Out-File: 将输出的内容放置到文件。主要是接受Pipeline过来的内容。

Out-File -FilePath d:\service.txt -InputObject (Get-Service)

Out-Gridview: 将数据导出到一个图形化的界面显示。
image

Out-Null:接收到的对象不会再不进行pipeline传输,屏幕也不显示所有的输出内容。

Out-String: 将获得的对象转为文本并显示到屏幕。

Export系命令

Export-Csv:导出csv文件。

get-process | export-csv -path d:\leo.csv
-append 附加信息到现有文件
-encoding:调整编码,解决乱码问题

Export-Clixml: 导出xml文件

Get-Service |Export-Clixml -path d:\leo.xml

Export-Clixml导出的信息比Export-Csv导出的更加全面。

Powershell信息的格式化输出

Format-List:以列表的形式显示内容。

Get-Service | Format-List -Property DisplayName,StartType,Status
DisplayName : Agent Activation Runtime_958d60
StartType   : Manual
Status      : Running

Format-Table: 用表格的形式显示内容。

Get-Service | Format-Table -Property DisplayName,Status

DisplayName                                                   Status
-----------                                                   ------
Agent Activation Runtime_958d60                              Running
AdobeUpdateService                                           Running
Adobe Genuine Monitor Service                                Running
Adobe Genuine Software Integrity Service                     Running
AllJoyn Router Service                                       Stopped

当内容超过屏幕的宽度的时候,无法显示出所有的列内容。

Format-Wide:只能显示一个属性的值,使用类似于填充宽度的方式进行显示,类似于dos的dir /w。使用价值不大。

Powershell的内容过滤

Where-Object对于管道传递过来的对象集合进行筛选,保留符合条件的对象。

get-process | Where-Object -Property name -eq notepad

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    365      25     8680      27612       0.31  22192   4 notepad

比较运算符 -eq , -ne, -le, -lt, -ge, -gt, -like, -in

get-service | Where-Object -Property name -in @('winrm', 'windefend')

Status   Name               DisplayName
------   ----               -----------
Stopped  WinDefend          Microsoft Defender Antivirus Service
Running  WinRM              Windows Remote Management (WS-Manag...

遍历集合中的对象

Foreach-Object 遍历对象集合中的所有对象。

$all_service = get-service | Where-Object status -eq 'running'
ForEach($service in $all_service){
          $service.name | Out-Host
}

posted on 2021-08-23 14:56  LeoZhangJing  阅读(1114)  评论(0编辑  收藏  举报

导航