您的位置:首页 > 运维架构 > Shell

PowerShell的学习笔记(1)

2017-01-30 22:07 357 查看
以前笔者Linux Shell脚本用的比较多;但是对于Window的Powershell脚本以前偶偶用过,但是用的不多;但是由于最近在学习研究Powershell DSC,而PowerShell DSC又是基于PowerShell的,所以重新对PowerShell进行了学习和整理,为了防止以后忘了一些对于自己不知道和了解的PowerShell的相关知识,所以记了这个笔记;请读者注意,这个笔记不会从头到尾把Powershell的东西都列出来,而是记一下对笔者有帮助的一些信息,如果读者想学习Powershell,请绕过;如果读者想知道笔者对那些重要的内容或者有意思的内容做了批注和笔记,到可以参考笔者的学习笔记。

@使用Show-Command 图像话显示Powershell cmdlet的用法

笔者以Powershell DSC的Start-DSCConfiguration命令为例子,演示Show-Command的用法

打开Powershell V4/V5,然后直接输入 Show-Command Start-DSCConfiguration,

然后Powershell 控制台就会弹出Start-DSCConfiguration的四种用法以及每个参数的意义。

请注意,Powershell不区分大小写。



@如何知道cmdlet的参数别名

我们知道,Powershell的cmdlet有别名;但是很少有人知道Powershell的cmdlet的参数也有别名。
下面就是一个例子,我们可以知道Get-EventLog cmdlet中的ComputerName参数别名为Cn
PS C:\Users\rodneyzhu.BEIJING> (Get-Command Get-EventLog | select -ExpandProperty parameters).ComputerName.aliases

Cn

@使用Test-Connection cmdlet代替Ping命令

我们在debug程序或者网络环境的时候,Ping命令是一个非常有用外部命令,但是Powershell的Test-Connection cmdlet也是一个测试网络连接的有用的命令,其描述如下
DESCRIPTION

    The Test-Connection cmdlet sends Internet Control Message Protocol (ICMP) echo request packets, or pings, to one

    or more remote computers and returns the echo response replies. You can use this cmdlet to determine whether a

    particular computer can be contacted across an IP network.

    You can use the parameters of Test-Connection to specify both the sending and receiving computers, to run the

    command as a background job, to set a time-out and number of pings, and to configure the connection and

    authentication.

    Unlike the familiar ping command, Test-Connection returns a Win32_PingStatus object that you can investigate in

    Windows PowerShell. You can use the Quiet parameter to force it to return only a Boolean value.

PS C:\Users\henry> Test-Connection www.baidu.com

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)

------        -----------     -----------      -----------                              -----    --------

Henry-LAP www.baidu.com   183.232.231.173                                           32       60

Henry-LAP www.baidu.com   183.232.231.173                                           32       59
Henry-LAP www.baidu.com   183.232.231.173                                           32       80
Henry-LAP www.baidu.com   183.232.231.173                                           32       54

@cmdlet和函数的区别

cmdlet是一个原生的Powershell命令行工具,该术语仅仅存在于Powershell和类似C#的.NET Framework语言中。换句话说,cmdlet仅仅出现在Powershell中
函数和cmdlet类似,但是不是以.NET语言编写,而是以Powershell自己的脚本语言编写。
应用程序是人员类型的外部可执行程序,包括PING,IPConfig等命令工具
命令是一个通用的术语,用于代表任何偶这所有上面的提到的术语

@搜索命令的三种方式

可以通过下面三种方式搜索PowerShell的cmdlet,以搜索出所有的带export动词前缀的powershell cmdlet为例子
Get-Help export*
Get-command export* 
Get-command -verb export

@Powershell的Provider(提供程序)

我们可以把文件系统,注册表,数据库,环境变量都称之为提供程序者。
提供程序者的关键字是Item(项)
PS C:\dsc> get-command *item*

CommandType     Name                                               Version    Source

-----------     ----                                               -------    ------

Function        Get-DAEntryPointTableItem                          1.0.0.0    DirectAccessClientComponents

Function        New-DAEntryPointTableItem                          1.0.0.0    DirectAccessClientComponents

Function        Remove-DAEntryPointTableItem                       1.0.0.0    DirectAccessClientComponents

Function        Rename-DAEntryPointTableItem                       1.0.0.0    DirectAccessClientComponents

Function        Reset-DAEntryPointTableItem                        1.0.0.0    DirectAccessClientComponents

Function        Set-DAEntryPointTableItem                          1.0.0.0    DirectAccessClientComponents

Cmdlet          Clear-Item                                         3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Clear-ItemProperty                                 3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Copy-Item                                          3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Copy-ItemProperty                                  3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Get-ChildItem                                      3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Get-ControlPanelItem                               3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Get-Item                                           3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Get-ItemProperty                                   3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Get-ItemPropertyValue                              3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Invoke-Item                                        3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Move-Item                                          3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Move-ItemProperty                                  3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          New-Item                                           3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          New-ItemProperty                                   3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Remove-Item                                        3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Remove-ItemProperty                                3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Rename-Item                                        3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Rename-ItemProperty                                3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Set-Item                                           3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Set-ItemProperty                                   3.1.0.0    Microsoft.PowerShell.Management

Cmdlet          Show-ControlPanelItem                              3.1.0.0    Microsoft.PowerShell.Management

@Powershell获取对象的所有的属性(列名)

咱们以Get-Process为例子,如何获取Get-Process返回的对象的所有的属性名称?通过Get-Member
Get-Process | Get-Member 下面是其部分输出;

PS C:\Users\rodneyzhu.BEIJING> Get-Process | Get-Member

   TypeName: System.Diagnostics.Process

Name                       MemberType     Definition

----                       ----------     ----------

Handles                    AliasProperty  Handles = Handlecount

Name                       AliasProperty  Name = ProcessName

NPM                        AliasProperty  NPM = NonpagedSystemMemorySize64

PM                         AliasProperty  PM = PagedMemorySize64

SI                         AliasProperty  SI = SessionId

VM                         AliasProperty  VM = VirtualMemorySize64

WS                         AliasProperty  WS = WorkingSet64

Disposed                   Event          System.EventHandler Disposed(System.Object, System.EventArgs)

ErrorDataReceived          Event          System.Diagnostics.DataReceivedEventHandler ErrorDataReceived(System.Objec

Exited                     Event          System.EventHandler Exited(System.Object, System.EventArgs)

OutputDataReceived         Event          System.Diagnostics.DataReceivedEventHandler OutputDataReceived(System.Obje

BeginErrorReadLine         Method         void BeginErrorReadLine()

BeginOutputReadLine        Method         void BeginOutputReadLine()

CancelErrorRead            Method         void CancelErrorRead()

CancelOutputRead           Method         void CancelOutputRead()

Close                      Method         void Close()

如果想知道MemberType有哪几种类型呢?
Get-Process | Get-Member | Select-Object  -Property MemberType -unique

PS C:\Users\rodneyzhu.BEIJING> Get-Process | Get-Member | Select-Object  -Property MemberType -unique

    MemberType

    ----------

 AliasProperty

         Event

        Method

  NoteProperty

      Property

   PropertySet
ScriptProperty

@普通的Powershell的格式化输出以及原理本质

Powershell在控制台中的输出格式,全部是由C:\windows\System32\WindowsPowerShell\v1.0\DotNetTypes.format.ps1xml文件控制的。
通过下面的命令,可以查看其输出的格式定义。

PS C:\Users\rodneyzhu.BEIJING> cd $PSHOME

PS C:\windows\System32\WindowsPowerShell\v1.0> notepad .\DotNetTypes.format.ps1xml

PS C:\windows\System32\WindowsPowerShell\v1.0>

因为Get-Process返回的是一个System.Diagnostics.Process的对象,其属性的输出格式定义在DotNetTypes.format.ps1xml文件中如下,

<View>
<Name>process</Name>
<ViewSelectedBy>
<TypeName>System.Diagnostics.Process</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Handles</Label>
<Width>7</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>NPM(K)</Label>
<Width>7</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>PM(K)</Label>
<Width>8</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>WS(K)</Label>
<Width>10</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>VM(M)</Label>
<Width>5</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Label>CPU(s)</Label>
<Width>8</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Width>6</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader>
<Width>3</Width>
<Alignment>right</Alignment>
</TableColumnHeader>
<TableColumnHeader />
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>HandleCount</PropertyName>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>[long]($_.NPM / 1024)</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>[long]($_.PM / 1024)</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>[long]($_.WS / 1024)</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>[long]($_.VM / 1048576)</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<ScriptBlock>
if ($_.CPU -ne $())
{
$_.CPU.ToString("N")
}
</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Id</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>SI</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ProcessName</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>

@定制的格式化输出中的有用的命令

Format-Table(ft),Format-List(fl)和Format-Wide可以用来格式化列表。

#1 -autoSize 

Get-WmiObject Win32_BOIS | Format-Table -autoSize

#2 -GroupBy 分组

Get-Service |Sort-Object Status | ft -GroupBy status

#3 -wrap 把隐藏显示的信息显示出来

 Get-Service |ft -AutoSize -Wrap

#4  format-list 水平的显示对象信息

Get-Service | Format-List

#5 Format-Wide 只能接受一列的属性作为输入

PS C:\windows\System32\WindowsPowerShell\v1.0> Get-EventLog Security| select -last 10|Format-Wide Message -col 4

A handle to an object was ... A handle to an object was ... A handle to an object was ... A handle to an object was ...

A handle to an object was ... A handle to an object was ... A handle to an object was ... A handle to an object was ...

A handle to an object was ... A handle to an object was ...

@新增加新命名的列(通过@ hash表实现)

对于Hash表,啰嗦两句(不区分大小写):对于名字,可以接受,N,L和Lable;对于表示式,可以接受E

PS C:\windows\System32\WindowsPowerShell\v1.0> Get-Process | Ft Name,@{n='VM(MB)';e={$_.VM/1MB -as [int]}} -AutoSize

Name                               VM(MB)

----                                     ------

atieclxx                               94

atieclxx                               82

atiesrxx                               36

chrome                                 65

chrome                                 63

chrome                                764

chrome                                182

chrome                                194

chrome                                199

chrome                                426

chrome                                262

chrome                                640

chrome                                433

communicator                     244

conhost                                25

conhost                                26

另外,对于format-table,还能接受,FormatString(主要用于数值和日期,其具体的格式化类型代码,可以通过这个网站查询https://msdn.microsoft.com/en-us/library/26etazsy.aspx),下面来一个例子。

PS C:\windows\System32\WindowsPowerShell\v1.0> Get-Process|Format-Table Name,@{n='VM(MB)';e={$_.VM};formatstring='F2';al

ign='right'} -autosize

Name                                     VM(MB)

----                                     ------

atieclxx                            98234368.00

atieclxx                            85872640.00

atiesrxx                            37621760.00

chrome                              68382720.00

chrome                              65572864.00

chrome                             810106880.00

chrome                             191049728.00

chrome                             212156416.00

chrome                             208486400.00

chrome                             446398464.00

chrome                             274321408.00

chrome                             722882560.00

chrome                             454279168.00

chrome                             335695872.00

@Out-GridView 弹出GridView窗体显示信息且能添加过滤条件

 Get-EventLog Security |select -last 10 | Out-GridView



@通过Invoke-Command和Enter-PSSession方法远程执行命令

Invoke-Command通过WSMan(Web Service Management)协议访问目标节点上的WinRM上暴露端口5985或者5986,且是并行执行。
下面是一个范例:
Invoke-Command -ComputerName Server-R2,Server-DC4,Server12 -command {Get-EventLog Security -Newest 20 | where $_.EventID -EQ 1212}

Enter-PSSession和Invoke-Command类似,只不过Enter-PSSession只能同一时刻连接一台计算机,而Invoke-Command可以同时连接多台计算去执行命令。
下面是一个范例:
Enter-PSSession -ComputerName Server-R2 执行这个命令后,会直接进入到远程计算机上。

@遍历对象集合和调用对象的方法

PowerShell中,可以通过foreach-object cmdlet遍历一个PowerShell对象集合;可以通过$_.<方法名称>调用其内部的方法。
下面是一个停止所有服务名包含“BI”字母的服务的5中不同实现方式。

Get-Service -name *BI* | Stop-Service
Get-Service -name *BI* | ForEach-Object{$_.Stop()}

Get-WmiObject Win32_Service -filter "name LIKE '%BI%'" | Invoke-WmiMethod -name StopService
Get-WmiObject Win32_Service -filter "name LIKE '%BI%'" | ForEach-Object{$_.StopService()}

Stop-Service -name *BI*

Get-Service -name *BI* | Stop-Service
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Powershell