`
gk23
  • 浏览: 171403 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

powershell notes

阅读更多

   命令模式        //字符串不需要加引号,除变量和圆括号中的内容外的所有内容均可看作字符串
       copy users.txt accounts.txt
       copy $src $dest
       write-host 2+2

   表达式模式      //以最高级别语言分析方法来进行分析:若为数字,则原样表示该数字;若为字符串,则需要加引号
       2+2
       "Hello" + " world"
       $a = "hi"
       $a.length * 13

   混合模式        //模式发现过程从圆括号内开始
       Write-Host ((Get-Date) - (Get-Date).date)

命令解析优先级

   别名
   函数
   cmdlet
   脚本
   可执行文件
   正常文件


" "     //双引号中将尝试替换匹配的变量值
' '     //单引号中不进行变量值替换
@" "@   // "here string",其中可包含任意字符(包括回车和引号),将尝试替换匹配的变量值
@' '@   // "here string",其中可包含任意字符(包括回车和引号),不进行变量值替换
{ }     //大括号中将不进行变量值替换,类型为 System.Management.Automation.ScriptBlock
       //注意:" "、' '、{ } 有时可以达到相同的效果,但是它们完全不一样
   $field = { $var = 1 }
( )     //求值,用于混合模式
   $($Name)
$( )    //求值并返回结果为对象数组
   $( )        //返回空值
   $(1,2,3)    //返回包含 1、2、3 的数组
       $(0,1,2)[1]
   $(Get-Alias a*) 返回表达式的计算结果
@( )    //同 $( )

[ ]     //类型运算符
   [int]
   [single]
   [double]
   [string]
  
:label      //标签,用于控制结构或代码块
·       //换行符号
.       // Dot Sourcing,允许在当前作用域(而不是本地作用域)中运行函数、脚本块和脚本
       // . 后可以使用 [string] 或者 [ScriptBlock]
   . { $var = value; }
   . "func"
&       //调用运算符或者说是函数转义运算符
       // & 后可以使用 [string] 或者 [ScriptBlock]
   & { $var = value; }         //代码块 ScriptBlock 可以作为无名函数用 & 运算符调用
   & "func"
   Function Cook ( $i, $f ) { &$f $i; }        //函数名可以作为参数传递,然后用 & 运算符进行转义
       Cook Chicken { Param($x) Alert "Boom $x" }
   "Hi" | & { begin { "Beginning" } process { write-host "Boom $_" } end { "Ending" } }
%       // ForEach-Object
   $words | % { $h=@{} } { $h[$_] += 1 }
?       // Where-Object


转义序列
   `0      //空值
   `a      //警报
   `b      //退格
   `f      //换页
   `n      //新行
   `r      //回车
   `t      //制表符
   `v      //垂直引号
   ``      // "`"
   ````[   // "["
   '``['   // "[",' ' 阻止了转义的进行
  

数字常量
   1kb     // 1024
   1mb
   1gb
   1e3     // 1000
   0xFFFF  // 65535
  

Windows PowerShell 自动变量
   $$                  //前一命令行的最后一个标记
   $?                  //上一命令的布尔状态
   $^                  //前一命令行的第一个标记
   $_                  //当前管道对象
   $Args               //为脚本或函数指定的参数
   $ConfirmPreference
       $ConfirmPreference = "low"
   $Error              //先前命令中的错误数组
       $Error[0]           //前一次错误
       $Error[1]           //倒数第二次错误
   $Foreach            //引用 foreach 循环中的枚举器
   $Home               //用户的主目录
   $Host               //引用宿主 POWERSHELL 语言的应用程序
       $Host.privatedata       // current colors
   $Input              //通过管道传递给脚本的对象的枚举器
   $LastExitCode       //上一程序或脚本的退出代码
   $Matches            //使用 –match 运算符找到的匹配项的哈希表
   $OFS                //分隔符
       [string][char[]]"power"     // [char[]] 转型为 [string] 时会用 $OFS 作为字符之间的分隔符
   $OutputEncoding     // When we pipe output data from PowerShell cmdlets into native applications, the output encoding from
                       // PowerShell cmdlets is controlled by the $OutputEncoding variable, which is by default set to ASCII.
       $OutputEncoding = [Console]::OutputEncoding
   $PSHome             // Windows PowerShell 的安装位置
   $profile            //标准配置文件(可能不存在)
   $StackTrace         // Windows PowerShell 捕获的上一异常
   $Switch             // switch 语句中的枚举器


通配符
   *           //与 0 或更多出现的字符匹配
   ?           //仅与一个字符匹配
   [ - ]

类型
   空类型
       [void]
   数值类型
       [byte]        typeof(byte)
       [decimal]     typeof(decimal)
       [double]      typeof(double)
       [float]       typeof(float)
       [int]         typeof(int)
       [long]        typeof(long)
       [single]      typeof(float)
   字符类型
       [char]        typeof(char)
       [string]      typeof(string)
   布尔类型
       [bool]        typeof(bool)
   集合类型
       [array]       typeof(System.Array)
                     typeof(System.Object[])
       [hashtable]   typeof(System.Collections.Hashtable)
   其它
       [psobject]    typeof(System.Management.Automation.PSObject)
       [ref]         typeof(System.Management.Automation.PSReference)
       [regex]       typeof(System.Text.RegularExpressions.Regex)
       [scriptblock] typeof(System.Management.Automation.ScriptBlock)
       [switch]      typeof(System.Management.Automation.SwitchParameter)
       [type]        typeof(System.Type)
       [wmi]         typeof(System.Management.ManagementObject)
       [wmiclass]    typeof(System.Management.ManagementClass)
       [wmisearcher] typeof(System.Management.ManagementObjectSearcher)
       [xml]         typeof(System.Xml.XmlDocument)
           $var = [xml] "<top><a>one</a><b>two</b><c>3</c></top>"
           $var.top
           $var.top.a
           $var.top.a = "13"

作用域     //可用于变量及函数
   function global:prompt { }
   global      //全局作用域中的变量对所有作用域均可见
   script      //脚本作用域中的变量只对该脚本文件中的所有作用域可见
   local       //本地作用域中的变量仅在当前作用域及其子域中可见
   private     //私有作用域变量仅对当前作用域可见

变量            //可以定义作用域及类型
   [void] $var     //可以阻止变量 $var 的输出
       [void] [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" )
   [int] $global:var = 1.0
   [int[]] $global:var = (1,2)
   [regex] $regex = "\s{1}"       //正则表达式类
   $global:var = [int]1.0      // var 无类型
   [float] [int] $var = 1      // var 是 float 类型
   ([DateTime]"1/1/2007" -[datetime]::now).days
   ${C:\TEMP\testfile.txt} = "string"      //写入文件
   ${C:\TEMP\testfile.txt} += "string"     //追加写入文件
   ${function:func} = {}
   $block = { Get-Process; $a=1; }         //变量可以存储 code block
   $type = [string]                        // type 为 System.RuntimeType 型变量
       $MsgBox = [Windows.Forms.MessageBox]
       $MsgBox::show("Hello world","Demo Msg Box",$button,$icon)
   $AppLog = New-Object -TypeName System.Diagnostics.EventLog -ArgumentList Application
   $AppLog | Get-Member -MemberType Method
   $null       //空变量,占位用
       $object = $null                         //删除变量的值,并不等价于 Remove-Variable var
       ($grp.Member).add($NewUserDN) > $NULL   //也可用于进行重定向操作
       $null = Get-Command help

调用 method、Property
   $object.Property
   $object.method()
   $object.$methodnamestring.Invoke()
       foreach ( $method in "ToUpper", "ToLower", "GetType" ) { $s.$method.Invoke() }
   [ static object ]::Property
   [ static object ]::method()
  

取得对象
   $object | Get-Member
   [ static object ] | Get-Member -Static
   $var.gettype()
       $var.gettype().fullname
  

bool 值
   $TRUE   //非空字符串("false"除外);所有不等于 0 的数字;长度大于 1 的数组;长度为 1,其元素为 TRUE 的数组 ;对所有对象的引用
   $FALSE  //空字符串或字符串 "false" ;所有等于 0 的数字  ;长度为 0 的数组  ;长度为 1,其元素为 FALSE 的数组;空值


数组
   @( )            //空数组
   @(2)            // 1 个元素的数组
   1,(2,3),"4"     //数组包含数组
   $array          //数组内的所有元素
   $array[0]
   $array[-1]      //最后一个元素
   $array[-2]      //倒数第二个元素
   $array[1][2]    //对二维数组进行索引
   $array[2..20]
   $array[20..2]
   $array[-2..-20]
   $array[-20..-2]
   Get-Member -inputobject $array  //针对数组 array
   $array | get-member             //针对数组中的每个元素
  
关联数组(哈希表)
   @{ }            //创建空哈希表
   @{foo=1;bar=2}  //创建并初始化哈希表
   $hash           //哈希内的所有元素
   $hash.foo
   $hash["foo"]
   $hash.psbase.keys       //返回键值数组
       $hash.psbase.keys | sort { $hash[$_] }
  

运算符     //根据第一个参数的类型选择重载运算符
   比较运算符       //用于字符串、整型
       -eq、-lt、-gt、-le、-ge、-ne
           -ieq    //不区分大小写
           -ceq    //区分大小写
       -like
           "file.doc" -like "f*.doc"
       -notlike
       -contains
           1,2,3 -contains 1
       -notcontains
   逻辑运算符
       -and、-or、-not、!
   数组运算符
       –contains
           1,2,3,5,3,2 –contains 3     //数组中是否包含 3
       -eq、-lt、-gt、-le、-ge、-ne
           1,2,3,5,3,2 –eq 3           //返回所有等于 3 的元素
   赋值运算符
       =、+=、-=、*=、/=、%=
   字符串运算符
       +           //连接两个字符串
       *           //按特定次数重复字符串
           "2" * 30
       -f          //设置字符串格式(.NET 格式说明符)
           "{0:N2}" -f 4671.60     //输出格式为 4,671.60
           "{0:F2}" -f 4671.60     //输出格式为 4671.60
           "{0:x}" -f 10           //输出格式为十六进制 a
           "{0:X}" -f 10           //输出格式为十六进制 A
           "{0,-12:N2}{1}string{0}" -f 77, 88  //输出格式为 77.00       88string77,12 表示 77 对应的整个字段长度为 12 个字符
           "{0,12:N2}{1}string{0}" -f 77, 88   //输出格式为        77.0088string77,12 表示 77 对应的整个字段长度为 12 个字符
       -replace    //替换运算符
           "abcd" –replace "bc", "TEST"
       -match      //正则表达式匹配
           $note -match '([A-G#]{1,2})(\d+)' | out-null
       -like       //通配符匹配
   类型操作运算符
       -is         //类型鉴别器
           $var -is [int]
       -as         //类型转换器
           $var = 1 -as [string]
   其它运算符
       ..
           $ips = 1..254 | ForEach-Object -Process {"192.168.1." + $_}
           [int][char]"a"..[int][char]"z"
       ,   //连接运算符,形成数组
           $contents = "Prefix", "Suffix"
           sum 1,2,3       // 1,2,3 作为数组参数
       -band       //二进制与
       -bor        //二进制或
       -bnot       //二进制非
      

结构
   break
   continue        // break、continue 可用于代码块、函数、脚本
   exit
       exit 0
       exit 31492
   for
       [:label] for ( [初始值]; [条件]; [迭代值] ) { }
           for ( $i = 0; $i –lt 5; $i++ ) { Write-Object $i; }
           for ( $i = 0; $i -lt $array.length; $i++ ) { Alert $array[$i]; }
   foreach
       [:label] foreach ( $var in set ) { }
           foreach ( $var in $array ) { Write-Output $var }
       Expression | foreach { }
           Get-Process | foreach { write-output $_ }
   function        //函数是可以嵌套的;函数的返回值是所有计算输出的结果,即返回的实际上是一个数组
                   //注意:如果去掉 function func 则为无名函数,调用时需要使用 & 运算符
       function func { write-output $args[0]; return 0; }         //匿名参数
       function func ( [string]$label = "default label", [int]$start = 0 ) { BEGIN { } PROCESS { } END{ } }
           func "label" 1          // func ( "label", 1 ) 的调用方法是错误的
           func -label "label" -start 1
           func -start 1 -label "label"
       function func { param ( $var ) if ( $var -gt 17 ) { return $true } else { return $false } }
       function func
       {   Param ( $var )
           Begin
           {   # Only gets process at the Beginning
               # Normally include Variable creation and functions
           }
           Process
           {   # Gets process for each object in the pipe (if ones exist)
               Write-Host "Hello $_";
           }
           End
           {   # Always get processed once at the end
           }
       }
       ${function:func} = {}
   filter      //编写带有 PROCESS 脚本块的函数的速记方式
       filter MyFilter ( [int]$start = 0 ) { $_.name }
   if
       if ( condition ) { } elseif ( condition) { } else { }
   param       //用于定义代码块或脚本的参数列表
   return      //可以返回的对象是 变量、cmdlet、函数、可运行程序或脚本文件
               //如果返回的对象是 cmdlet、函数、可运行程序或脚本文件则会先进行展开计算再返回值
               // return 的作用其实只是引起一个计算动作并退出而已
   switch      //在该脚本中可以使用变量 $_,$_ 表示当前正在计算的值。如果在 switch 中使用了数组,则将测试该数组的所有元素
       $var = "word1", "word2", "word3";
       Switch -regex ( $var )
       {   "word1"     { "Multi-match Exact " + $_; continue; };
           "w.*2"      { "Pattern match Exact " + $_; };
           default     { "Multi-match Default " + $_; };
       }
       Switch ( $var )
       {   "F" { continue; };
           "C" { continue; };
           "R" { continue; };
           "W" { continue; };
       }
   throw       //为脚本提供的功能等同于 ThrowTerminatingError API 为 cmdlet 提供的功能
               //接受字符串、异常或 ErrorRecord 作为参数
       throw "Danger, Danger"
   trap
       trap [ExceptionType]    // [ExceptionType] 可选,如果没有 [ExceptionType] 则表示对任何类型
       {   if ( ... )
           {   write-host "An error occured: "
               write-host "ID: " $_.ErrorID
               write-host "Message: "$_.Exception.Message
               continue;                           # 从导致 trap 的脚本语句之后的下一语句继续;
                                                   # $? 将更新,但不生成任何错误记录
           }
           else ( ... )
           {               # do something
               Break;      # 再次引发异常
           }
                           # 不执行 $ErrorActionPreference 设置中指定的任何操作
       }
   util
       do { } until ( condition )
   while
       [:label] while ( condition ) { }
       do { } while ( condition )


静态类
   System.Console
       [console]::Beep($freq, $duration)
       [Console]::OutputEncoding
   System.Environment      //用于当前进程
       [System.Environment] | Get-Member -Static
   System.Math             //数学运算
       [System.Math]::Sqrt(9)
       [System.Math]::Property
       [System.Math]::method( )
       [System.Math] | Get-Member -Static


Windows PowerShell 驱动器
   Alias
       Alias:
   Certificate
       Cert:
   Environment
       Env:
           $env:path
           $env:path += ";newdirectory"
   FileSystem
       C:
   Function
       Function:
   Registry    //注册表项中的项被认为是它们所在项的属性,使用 Get-ItemProperty cmdlet 可以检索它们
       HKLM:       // HKEY_LOCAL_MACHINE
       HKCU:       // HKEY_CURRENT_USER
   Variable    //所有的变量均为对象
       Variable:


标准参数
   帮助参数
       -?
           cmdlet -?       //等价于 get-help cmdlet
   通用参数        //由 Windows PowerShell 引擎进行控制,cmdlet 实现这些参数时,它们的行为方式将始终相同
       -Debug
       -ErrorAction
       -ErrorVariable
       -OutBuffer
       -OutVariable
       -PassThru           //打印出结果以进行确认
       -Verbose
       -Warn
       -whatif             //不执行命令就告诉你命令执行结果
       -WhatIfConfirm
   建议参数        // Windows PowerShell 核心 cmdlet 对类似参数使用标准名称
                   //尽管参数名称的使用不是强制的,但存在明确的用法指南以鼓励标准化
       -CaseSensitive
       -Exclude
       -Force
       -Include
       -PassThru
       -Path


alias
   cat/type            Get-Content
   cd/chdir            Set-Location
   clear/cls           Clear-Host
   copy/cp             Copy-Item
   del/rm/rmdir/erase  Remove-Item
   diff                Compare-Object
   dir/ls              Get-ChildItem
   echo/write          Write-Output
   h/history           Get-History
   kill                Stop-Process
   lp                  Out-Printer
   md/mkdir            New-Item
   mount               New-PSDrive
   move/mv             Move-Item
   popd                Pop-Location
   ps                  Get-Process
   pushd               Push-Location   
   pwd                 Get-Location
   r                   Invoke-History
   ren                 Rename-Item
   sleep               Start-Sleep
   sort                Sort-Object
  

   标准别名
       动词
           Get             g
           Set             s
       名词
           Item            i
           Location        l
           Command         cm
          
cmdlet          //名称组成:verb-noun。注意 function 也很有可能具有该名称结构,比如 clear-host
   *-Acl
       Get-Acl
       Set-Acl
      
   *-Alias
       Get-Alias
           Get-Alias cls
           Get-Alias | Where-Object {$_.Definition -eq "Set-Location"}
       Set-Alias
           Set-Alias -Name gi -Value Get-Item
           Set-Alias gh Get-Help
           Set-Alias np c:\windows\notepad.exe
  
   *-Command
       Get-Command
           Get-Command         //获取所有的 cmdlet
           Get-Command *       //返回所有可调用项的列表
           Get-Command *-service
           Get-Command -Name New-PSDrive -Syntax       //查看命令语法
           参数
               -CommandType
                   Get-Command -CommandType alias
                   Get-Command -CommandType function
                   Get-Command -Commandtype externalscript
               -Name
                   Get-Command -Name Clear-Host
               -Noun
                   Get-Command -Noun service
               -Syntax
                   Get-Command -Syntax *-service
               -Verb
                   Get-Command -Verb get
  
   *-Content
       Add-Content
       Get-Content         // Get-Content 已将从文件读取的数据视为一个数组,文件内容的每行上有一个元素
           Get-Content -Path C:\boot.ini
           (Get-Content -Path C:\boot.ini).Length
           $Computers = Get-Content -Path C:\boot.ini
       Set-Content
  
   *-Credential
       Get-Credential
      
   *-Date
       Get-Date
  
   *-Debug
       Set-PSDebug
           Set-PSDebug -Strict     //切换至 strict 模式
       Write-Debug
      
   *-ExecutionPolicy
       Get-ExecutionPolicy
       Set-ExecutionPolicy
           Set-ExecutionPolicy remotesigned
  
   *-Host
       Out-Host        //将数据直接发送到控制台
           Out-Host -Paging
               Get-ChildItem -Path C:\ | Out-Host -Paging
       Read-Host
           $var = Read-Host "What directory do you want to start at?"
  
   *-Item
       Copy-Item
           Copy-Item -Path C:\New.Directory -Destination C:\temp           //只复制容器
           Copy-Item -Path C:\New.Directory -Destination C:\temp -Recurse  //复制容器及其内容
           Copy-Item -Filter *.txt -Path c:\data -Recurse -Destination c:\temp\text
           Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu:
           Copy-Item -literalpath thumb[1].jpg junk.jpg
               -Force          //强制覆盖
       Get-ChildItem
           Get-ChildItem -Path C:\Windows
           Get-ChildItem -Path C:\Windows\?????.log
           Get-ChildItem -Path C:\Windows -Recurse -Include *.dll -Exclude [a-y]*.dll
           Get-ChildItem -Path hkcu:\
               -Exclude
               -Force          //强制列出隐藏项、系统项,包括注册表中的隐藏项、系统项
               -Include
               -Name           //仅显示 name 项
               -Recurse
       Get-Item
       Get-ItemProperty
           Get-ItemProperty -Path hklm:\SOFTWARE
           Get-ItemProperty -Path hklm:\Software -Name DevicePath
       Invoke-Item         //对文件或文件夹执行默认操作,其效果与在 Windows 资源管理器中双击该项的效果相同
           Invoke-Item C:\WINDOWS
       Move-Item
           Move-Item -Path C:\temp\New.Directory -Destination C:\ -PassThru
       New-Item
           New-Item -Path c:\temp\New.Directory -ItemType Directory
           New-Item -Path C:\temp\Newfile.txt -ItemType file
           New-Item -Path HKLM:\SOFTWARE\Microsoft\Test       //由于所有的注册表项都是容器,只需提供显式路径即可
       New-ItemProperty
           New-ItemProperty -Path hklm:\Software -Name PowerShellPath -PropertyType String -Value $PSHome
               -PropertyType
                   Binary          //二进制数据
                   DWord           //一个有效的 UInt32 数字
                   ExpandString    //一个可以包含动态扩展的环境变量的字符串
                   MultiString     //多行字符串
                   String          //任何字符串值
                   QWord           // 8 字节二进制数据
       Remove-Item
           Remove-Item alias:ls
           Remove-Item C:\temp\New.Directory -Recurse
           Remove-Item -Path 'hkcu:\key with spaces in the name'
           Remove-Item -Path HKCU:\CurrentVersion\* -Recurse
                                                   //删除 HKCU:\CurrentVersion 中的所有子项但不删除 HKCU:\CurrentVersion 本身
       Remove-ItemProperty
           Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome
       Rename-Item
           Rename-Item -Path C:\file1.txt fileOne.txt
       Rename-ItemProperty
           Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome
  
   *-Location
       Get-Location
       Pop-Location        // popd
       Push-Location       // pushd
           Push-Location -Path Temp        //将当前位置压入栈并且前进到 Temp 位置
       Set-Location
           Set-Location -Path C:\Windows
           Set-Location -Path HKLM:\SOFTWARE
  
   *-Member
       Add-Member      //增加的对象是针对对象实例而不是针对类型
       Get-Member
           Get-Process | Get-Member
           Get-Process | Get-Member -MemberType Properties
           Get-Member -inputobject $array      //针对数组 array
           $array | Get-Member                 //针对数组中的每个元素
           ( Get-Member -inputobject $object $x ).MemberType   //取得成员类型
           ( "hello" | Get-Member split ).definition           //取得成员定义
           [System.Environment] | Get-Member -Static           // System.Environment 是静态类,查看是必须加 static 参数
           -MemberType 参数
               AliasProperty
               All
               CodeMethod
               CodeProperty
               MemberSet
               Method
               Methods
               NoteProperty
               ParameterizedProperty
               Properties
               Property
               PropertySet
               ScriptMethod
               ScriptProperty
  
   *-Object
       ForEach-Object      //对多个对象重复同一任务
           Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process { ($_.FreeSpace)/1024.0 }
               //注意:$_.FreeSpace 的值并没有被改变
           $events | foreach-object -begin { get-date }
                                    -process { out-file -filepath events.txt -append -inputobject $_.message }
                                    -end { get-date }
       New-Object          //创建 .NET 和 COM 对象
           New-Object -TypeName System.Diagnostics.EventLog                            //创建对象引用
           New-Object -TypeName System.Diagnostics.EventLog -ArgumentList Application  //通过 ArgumentList 参数指定构造函数参数
           New-Object -ComObject WScript.Shell         // WScript.Shell 是 ProgId
           $rule = New-Object System.Security.AccessControl.FileSystemAccessRule( $Principal, $Right, "Allow" )
       Sort-Object
           Get-WmiObject Win32_SystemDriver|Sort-Object State,Name|Format-Table Name,State,Started,DisplayName -AutoSize -Wrap
           参数
               -Descending
       Tee-Object
           Get-Process notepad | Tee-Object -variable proc | Select-Object processname, handles
           Get-Process | Tee-Object -filepath C:\Test1\testfile2.txt
       Where-Object        //从管道中删除对象
           Get-Alias | Where-Object -FilterScript {$_.Definition -eq "Set-Location"}
           1,2,3,4 | Where-Object -FilterScript {$_ -lt 3}
           Get-WmiObject Win32_SystemDriver | Where-Object { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") }
           Get-Process | Where-Object -FilterScript { $_.Responding -eq $false } | Stop-Process
           Get-ChildItem -recurse | Where-Object {$_.extension -eq ".Log"}
  
   *-Path
       Convert-Path        //将路径从 Windows PowerShell 路径转换为 Windows 路径
       Join-Path           //将路径和子路径合并到单个路径中,提供程序将提供路径分隔符
       Resolve-Path        //解析路径中的通配符并显示路径内容
           ( resolve-path docs:/junk.txt ).ProviderPath
       Split-Path          //返回指定的路径部分
       Test-Path           //确定路径的所有元素是否存在
      
   *-Process
       Get-Process
           Get-Process -Name power*, exp*
           Get-Process -Id PID
       Stop-Process
           Stop-Process -Name t*, e* -Confirm      // Confirm 参数强制进行提示
  
   *-PSDrive
       Get-PSDrive
           Get-PSDrive -PSProvider FileSystem
           Get-PSDrive -PSProvider Registry
       New-PSDrive
           New-PSDrive -name MyDocs -psprovider FileSystem -root "$home\My Documents"
           New-PSDrive -name Uninstall -PSProvider Registry -Root HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
       Remove-PSDrive
           Remove-PSDrive -Name Office
  
   *-PSProvider
       Get-PSProvider
  
   *-Service
       Get-Service
           (get-service alerter).canpauseandcontinue
           (get-service schedule).stop( )
       Restart-Service
           Get-Service | Where-Object -FilterScript { $_.CanStop } | Restart-Service
       Start-Service
       Stop-Service
       Suspend-Service
  
   *-Transcript
       Start-Transcript
       Stop-Transcript
      
   *-Variable
       Get-Variable
           Get-Variable –scope 1 var       //从父作用域获取值
           Get-Variable –scope 2 var       //从祖父作用域获取值
       Remove-Variable
           Remove-Variable var         //等价于 $var = $null
           Remove-Variable -Name * -Force -ErrorAction SilentlyContinue
  
   *-WmiObject
       Get-WmiObject       //获取 WMI 对象
           Get-WmiObject -List     //检索所有类名称
           Get-WmiObject -List -ComputerName 192.168.1.29      //从指定计算机检索 wmi 信息
           Get-WmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 -ComputerName .                //获得类引用
           ( Get-WmiObject -List | Where-Object -FilterScript { $_.Name -eq "Win32_OperatingSystem" } )    //获得类实例
           Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .
           ( Get-WmiObject -Class Win32_OperatingSystem -ComputerName . ).InvokeMethod( "Win32Shutdown", 0 )
          
   Export-*
       Export-Alias
       Export-Clixml
       Export-Console
           Export-Console file
       Export-Csv
  
   Format-*        //格式化输出视图,都使用同一参数名称 Property 来指定要显示的属性
       Format-Custom
       Format-List         // Format-List cmdlet 以列表的形式显示对象,并在单独行上标记和显示每个属性
           Get-Process -Name powershell | Format-List
           Get-Process -Name powershell | Format-List -Property ProcessName, FileVersion, StartTime, Id
           Get-Process -Name powershell | Format-List -Property *
       Format-Table
           Get-Process -Name powershell | Format-Table -Property Path, Name, Id, Company
           Get-Process -Name powershell | Format-Table -Property Path, Name, Id, Company -AutoSize
           Get-Process -Name powershell | Format-Table -Property Path, Name, Id, Company -AutoSize -Wrap
           Get-Process -Name powershell | Format-Table -Property Path, Name, Id -GroupBy Company -AutoSize -Wrap
       Format-Wide         //默认情况下,Format-Wide cmdlet 仅显示对象的默认属性。与每个对象相关联的信息将显示在单独一列中
           Get-Process -Name powershell | Format-Wide -Property Id
           Get-Command | Format-Wide -Property Name -Column 1          //强制只进行 1 列的显示
  
   Get-*
       Get-Help
           Get-Help cmdlet     //等价于 cmdlet -?
           Get-Help *-Service
           Get-Help about_*    //显示有关 Windows PowerShell 中的概念性主题的信息,概念性帮助主题以 about_ 前缀开头
           Get-Help provider
               Get-Help registry
           参数
               -detailed
               -examples
               -full
               -parameter totalcount
  
   Invoke-*
       Invoke-Expression       //运行以字符串形式提供的 Windows PowerShell 表达式
       Invoke-History          //从会话历史记录中运行命令
       Invoke-Item             //对指定项调用特定于提供程序的默认操作
           Invoke-Item C:\Test\word.doc
      
   Measure-*
       Measure-Command         //度量运行脚本块和 cmdlet 所用的时间
       Measure-Object          //度量对象的特征及其属性
      
   Out-*           //重定向数据,Out cmdlet 应始终出现在管道末尾
       Out-File
           Get-Process | Out-File -FilePath processlist.txt
           Get-Process | Out-File -FilePath processlist.txt -Encoding ASCII
           Get-Process | Out-File -FilePath processlist.txt -Width 2147483647
           Get-Process > processlist.txt
       Out-Null            //放弃其接收的任何输入,但不会放弃错误输出
       Out-Printer         //打印数据。如果未提供打印机名称,则 Out-Printer cmdlet 将使用默认打印机
      
   Select-*
       Select-Object       //创建新的自定义对象,包含的属性是从用于创建他们的对象中选择的,对象的方法则保持不变
           Get-WmiObject -Class Win32_LogicalDisk | Select-Object -Property Name, FreeSpace
           Get-WmiObject Win32_LogicalDisk|Select-Object Name,FreeSpace|ForEach-Object {$_.FreeSpace = ($_.FreeSpace)/1024.0; $_}
       Select-String       //识别字符串中的模式
          
   write-*
       Write-Error         //将对象写入错误管道
       Write-Host          //使用主机用户界面来显示对象
       write-output        //将对象写入成功管道
           $data = @( get-service | write-output )     //将结果中的成功输出写入变量 $data


function
   Clear-Host
   help
   man
   more
       Get-Command | more
       more c:\boot.ini
   prompt
   TabExpansion        //控制 Tab 扩展
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics