powershell 学习笔记

2023-10-30

命令模式        //字符串不需要加引号,除变量和圆括号中的内容外的所有内容均可看作字符串
       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 扩展

 

 

 

学习疑问:
1.        如何任意显示某个对象的method并使用它呢(已结)?
2.        获取可卸载程序的命令行字卸载符串该怎么在powershell中使用呢?
一.        PowerShell常用快捷键
F7 :显示曾经输入的命令历史记录,用上下箭头可逐个选定再次执行。
ALT+F7 :清除命令历史记录。
ESC :清除当前输入的所有字符。
CTRL+END :清除从光标到行尾的内容。
CTRL+C / CTRL+BREAK :终止命令的执行。
↑ :向上查询历史命令。
↓ :向下查询历史命令。

二.        资源列表
1.www.powershell.com
:可下载powershell plus工具,比微软提供powershell工具方便,后者没有联想功能。
2.forums.microsoft.com/china
3.PowerShell网志:vista.itech.net
4.安装PowerShell: www.microsoft.com/downloads
5. PowerShellPowerShell 开发组博克http://blogs.msdn.com/PowerShell/
6. PowerShell新闻组Microsoft.Public.Windows.PowerShell
7. 脚本中心
http://www.microsoft.com/technet ... /msh.mspxPowerShell
8.
三.        什么是PowerShell
PowerShell是系统管理和脚本语言发展的未来。
它是微软提供的命令行界面的交互式Shell环境(新一代命令解析器)和脚本语言,使命令行用户和脚本编写者(通过对COM对象的编写来实现众多功能)都可以利用.NET FrameWork的强大功能(如.NET FrameWork的类库---FCL),帮助管理员完成弹性化和自动化的工作。
PowerShell是构建于.NET上的,所以安装需要.NET FrameWork v2.0的支持。
PowerShell是基于对象的,命令的输出即位对象。
PowerShell安装在%systemroot%/system32/下
四.        PowerShell的变量与参数
Powershell中的变量应理解为对象,而非文本。
定义变量的符号:$ 。如定义变量var用$var。为变量赋值$var = 123 $var1 = abd。还可以将变量嵌入到变量中去,如$var2 = “$var $var1”,$var2的值是 123 abd,如果是$var2 = ‘$var $var1’,则$var $var1被当成字符串赋给了$var2。记住单引号和双引号的区别。
对于数据类型可以不定义和声明。
查看所有变量:get-variable
查看对变量可操作的命令集:get-command –noun varibale
常用系统变量:$pshome   $home    $profile
变量的四种模式:local    script    global    private。
例:对环境变量的相应操作
Get-childitem env:
例:对环境变量的具体引用
$env:os
#说明CMD.EXE中的系统环境变量仍然可在powershell中使用

-        :参数引导符,比如有一参数Name,则书写时必须是  -Name
通用参数包括:WhatIf  Confirm  Verbose  Debug  Warn  ErrorAction  ErrorVariable
              OutVariable  OutBuffer,它们都是由powershell引擎控制的,每次cmdlet
              实现这些参数时,它们的行为始终相同。
-Syntax   :获得cmdlet的语法,如get-process –syntax

重要参数说明
-noun 可以获得影响同一类型对象的一系列命令
-passthru 可以看到命令的执行过程
-whatif 可以预览命令可能导致的后果,该参数可以实现对prototype原型模式的引用,不是每个cmdlet都可以使用该参数的.
-credential 指定用户帐户名称
-eq 等于运算符,加I –ieq表示不区分大小写比较;-ceq 区分大小写比较。
五.PowerShell的cmdlets与技巧
cmdlets命名规则:[动词-名词]
单个的cmdlets只能完成单任务,要完成复杂的任务必须通过管道 | 来完成。| 除了完成前1个cmdlets的执行结果到下1个cmdlets的传递作用,还起到命令的连接作用,即命令可以分行书写,便于阅读。
| :是并发执行的。
Aliases :别名。如gps=get-process sort=sort-object ft=format-table,可自定义命令的别名,命令为Get-Alias  -Name gi  -Value Get-Item,注意,系统自定义的别名如gi gcm scm等不能被更改。
命令缩写:为便于记忆,Set用S,Get用G,Item用I,Command用CM。如get-command=gcm;get- wmiobject=gwmi   etc.
Get-command :获得所有可用的cmdlets,注意不包括aliases function script等。
例:想获得alias/ function /script命令的详细信息
get-command –commandtype  alias/function/externalscript
get-aliases    :获得所有命令的aliases。
get-help      :获得帮助。
例:获得命令的帮助信息和它的语法
get-help –name get-command –full/-detail  -syntax
#-name  :可以省略
get-process -?
例:help或man分屏显示命令的帮助信息
help  get-service  或   man  get-service
例:利用more函数来分屏显示
get-process | more
#more也可以读取文件的内容分屏显示,如more  c:/test.txt
例:显示概念性主题的帮助信息
get-help  about_*
#about_  :表示概念性主题的前缀
get-help  about_where
#显示特定概念主题 where 的帮助信息
例:get-command *_service
#获得有关service操作的cmdlets
#_可以去掉,写成*service,但不能去掉*,写成get-command service,会出错的!
例:获得影响同一对象类型的一系列命令
get-command –noun  service
#-noun  :该参数可获得影响同一对象类型的一系列命令,类似get-command *service
例:get-service | get-member
#如果要充分了解get-service的对象结构,可通过|将该命令输出到get-member上
例:获得某命令输出对象的某些
get-process –name powershell | format-table –property processname,fileversion,starttime,name,id,company,path  –autosize  -wrap –groupby company
# -property 对于获取输出对象的信息很有用!
# -autosize表示自动调整列宽
# -wrap表示显示不下的列自动换行
#-width 2147483647防止表格因宽大而被截断
# -groupby用于控制表格输出,基于指定的属性值分组,易于显示很大的难于显示的表
# -autosize和-wrap连用显示效果不错,但很消耗系统资源,建议将宽度比较小的#property如name放到最后比较好
#如果想显示所有property可用*表示
#
例:获得某服务/进程的具体信息
get-service –name alerter/get-process -name powershell
例:列出动词get的所有命令
get-command –verb get
#verb  :参数的意思
例:列出当前目录下的文件夹和文件
get-childitem
#get-childitem  c:/   列出C盘下的目录和文件
#get-childitem c:/ | out-host 将C盘下的目录和文件输出到屏幕上,如果输出信息很多,该操作很消耗CPU和内存,可通过-paging参数来单屏输出。
#out-null   屏蔽输出;out-printer  打印输出
例:输出控制命令format-wide/format-list/format-table/format-custom
例:输出控制命令out-host/out-null/out-printer/out-file -Encoding ASCII –width 2147483647
get-process | format-table | out-file –filepath c:/test.txt
#将get-process输出到c:/test.txt上
#注意out-file默认将创建unicode, -Encoding ASCII是将文件改为ASCII,便于使用
#ASCII文件的工具处理输出
#-width 2147483647防止表格因宽大而被截断
例:要查看get-process的对象结构
get-process | get-member | out-host –paging
例:要查看get-process的对象结构中某一类型信息
get-process | get-member –membertype property
# MemberType 允许使用以下值:AliasProperty、CodeProperty、Property、NoteProperty、ScriptProperty、 Properties、PropertySet、Method、CodeMethod、ScriptMethod、Methods、 ParameterizedProperty、MemberSet 和 All。

探索发现
Get-Help, Get-Command
    Get-Member :查看“对象的结构”,很重要。
   
面向对象的小命令
Compare, Group, Measure, Select, Sort, Tee, Where
格式控制
Format-(Custom, List, Table, Wide)
面向任务的命令
进程:get/stop(-process)
系统服务:get/start/stop/suspend/resume/restart(-service)
事件日志:get-eventlog

  CLI(命令行接口)中的主要命令(????---不理解---??????)
– Shell Functions (CLI 可用代码)
– PowerShell Scripts (.PS1)
– Native commands (.EXE, .BAT, etc.)
使用Whanif预览执行结果:比如关闭某进程会对系统产生影响,就用它先预览一下。
$? :测试命令的执行成功与否。
重点:
并不是所有符合“动词-名词”命令规范都是PowerShell的cmdlet,例如clear-host,它是power-shell的内部函数。可通过get-command –name clear-host来判定其commandtype是function还是cmdlet。
除了cmdlet是PowerShell内置命令外,aliases  function  scirip  可执行文件和已注册文件类型处理程序的外部文件都归于powershell的命令。
PowerShell中的命令没有联想功能,但可通过TAB来扩展,条件是输入“动词+连字符-”之后,按TAB键就会自动找第一个匹配的命令,如果不是需要的,可再通过TAB来完成”。
六.对文件系统操作的命令
get-location  #获得当前目录
set-location –path  c:/ #将当前目录更改为c:/,但没有任何过程提示
set-location  -path  c:/ -passthru ##将当前目录更改为c:/,有过程提示
set-locaiton //server/共享目录 #server远程服务器
push-location  -path “local settings” #将当前目录压入堆栈,并将目录转到local settings下
push-location  -path temp  #将当前目录压入堆栈,并将目录转到temp
pop-location  -passthru #恢复被压入堆栈的目录,可通过它弹出最近使用过的目录
cd –path  hkcm:/software #将当前目录改为hkcm:/software

powershell用名词  项 表示驱动器下的内容,如果上文件系统驱动器,则项可以是“文件夹 或 文件 或 powershell的驱动器”。
对项常用操作命令:new-item rename-item copy-item remove-item invoke-item
invoke-item :执行项,它是有注册表中默认应用程序的处理程序(类似关联程序)
例:invoke-item c:/1.txt
# 调用notepad.exe打开1.txt,因txt默认关联程序是notepad.exe
    invoke-item c:/windows
# 等同于“双击打开windows目录”,关联资源管理器
    invoke-item c:/test.bat
# 执行bat
例:新建1.txt #new-item –path c:/1.txt –itemtype file/directory
例:将C盘下的1.txt重命名为D盘下的2.txt
rename-item –path c:/1.txt d:/2.txt
# 该命令错误,因为rename不能将目录移动,只能在本目录下重命名
# 正确:move-item –path c:/1.txt –destination d:/2.txt –passthru #可看具体移动过程
例:copy某目录
    copy-item –path c:/new –destination c:/temp
# 注意,如果new下有内容,则内容是无法拷贝到temp下,不加参数只复制容器
    copy-item –path c:/new –destination c:/temp –recurse –force –passthru
# -recurse表示将容器内的内容也拷贝过去
例:删除某目录
remove-item –path c:/temp –recurse
# 如果没有-recurse,删除目录需要确认
# 在不同命令下,-recurse有不同含义
get-command –noun item #获得项的所有操作命令
get-childitem :用来枚举“文件夹/文件/注册表”的。
例:set-location  [-path] c:/windows
    get-childitem [–name[  [-force[
    get-childitem  -recurse
#将当前目录定位到c:/windows
# 枚举当前目录下所有的文件(夹),但不包括子文件夹
# -name表示按名称筛选,即只显示文件名
# -force表示显示隐藏文件夹
# -recurse表示枚举目录下所有的文件(夹),包括所有子文件夹和子文件夹下的文件

如果需要更好的筛选,可以使用 –exclude  -include
例:查找/system32下的WINDOWS时间服务的DLL,它是w开头,中间有32字样
get-children –path c:/windows/system32/w*32*.dll –recurse –exclude *[9516]*.dll
# 使用-exclude *[9516]*.dll是为了排除与“win95或16位windows兼容的DLL
# 但是我在自己的机器上没有使用-exclude也没有显示有关与“win95或16位windows
# 兼容的DLL,我想这根windows的使用环境有关,设计语句毕竟要严谨和考虑全面
例:get-childitem –path c:/windows/*.dll –recurse –exclude [a-y]*.dll
#该语句不会返回任何结果,因为[a-y]*.dll中的通配符会排除所有DLL
#get-childitem –path c:/windows –include *.dll –recurse –exclude [a-y]*.dll

通配符
*   ?   和[ ]
其中[ ] 表示阔住匹配的字符
例:get-childitem  [-path] c:/windows/[xz]*
#表示枚举出c:/windows目录下所有以x或z打头的文件
例:get-childitem  [-path] c:/windows/?????.log
#表示枚举出c:/windows下所有5个任意字符的log文件
七.WMI对象操作
WMI是系统管理的核心技术。WMI类描述可管理的资源,很多类有很多属性。
get-wmiobject –list [–computername name/ip]  #获得本地或远程可用的WMI类资源
默认下get-wmiobject使用root/imv2命名空间,如果需要指定命名空间,必须使用-namespace
例:get-wmiobject –list –computernaem 192.168.1.1 –namespace root
例:具体使用某个WMI类win32_operatingsystem
get-wmiobject –class win32_operatngsystem –namespace root –computername
# 自己写的命令,错误在win32_operatngsystem少了i,root应root/cimv2
get-wmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 –ComputerName .
# . 表示WMI的样式,代表计算机名称
# 如get-wmiobject没有参数,默认第一个参数是class;参数namespace默认命名空间
# 是root/cimv2;针对本地操作参数computername可以省略
#该命令行可简写get-wmiobject win32_operatingsystem
可查看类的更多属性
get-wmiobject win32_operatingsystem | get-member –membertype property
查看非默认属性
get-wmiobject win32_operatingsystem | Format-Table -Property TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles
利用通配符缩写
get-wmiobject win32_operatingsystem | Format-table –Property total*,free*
#将table改为list,增强结果可读性

利用where-object  cmdlet管道筛选对象(利用比较运算符来进行)
在管道中,用 $_ 表示管道中的对象;用-表示比较运算符的前缀;用{}括住脚本块;用参数-filterscript进行过滤。
例:Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"} | Where-Object -FilterScript {$_.StartMode -eq "Manual"} | Format-Table -Property Name,DisplayName,pathname
该语句等同于
Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") } | Format-Table -Property Name,DisplayName

使用foreach-object cmdlet 对多个对象实施重复操作
例:Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {($_.FreeSpace)/1024.0/1024.0}

使用select-object对对象进行选择
例:get-wmiobject –class win32_logicaldisk | select-object –property name,freespace | get-member

使用sort-object排序
例:get-wmiobject –class win32_systemdriver | sort-object –property state,name | format-table –property name,state,started,displayname –autosize
#对format-tabel中输出的state和name property排序
#descending倒序排序
五.        .NET对象的操作
一些组件有.NET Framework和COM接口,powershell允许使用这些组件来扩展和增强系统管理工作
.NET Framework是一个类库,包含很多类,如System.Diagnostics.EventLog,该类可管理事件日志。
例:$applog=new-object –typename system.diagnostics.eventlog –argumentlist application,computername/ip
#将对象存储在变量中,便于调用
#没有-argumentlist,能建日志,但为空,加上参数就能建立对特定日志的管理
#输入变量$applog就可以看到日志个数
#–argumentlist application将application作为参数传递给参数-argumentlist,起到构造函数
#作用
# computername/ip访问远程日志
get-eventlog :查看日志
例:获得对象的方法 / 属性
$application | get-member –membertype method/property
#其中获得一个方法为 clear
清除日志信息
$application.clear()
#()必须加,clear()表示method,为了区分同名的property
例:查看applicatio最新的三个日志
get-eventlog –logname application –newest 3
#日志类型还有system  security
八..COM(组件对象模型)对象的操作
    COM组件包括WSH包含的库和Active X应用程序,new-object可以操作这些组件
New-object –comobject wscript.shell #创建COM对象
    # 还可创建WScript.Network、Scripting.Dictionary 和 Scripting.FileSystemObject
    例:利用COM对象创建快捷方式
    $shorcut=new-object –comobject wscript.shell
    #创建COM对象并将其保存到变量中
    $shorcut | get-member
    #获得对象的操作方法,其中包括createshortcut
$net=$shorcut.createshortcut(“c:/test.url”)  
#为建立的快捷方式建立 存放路径和名称
#注意,别落了后缀.url,还可以是.lnk,根据需要;另外记住()是紧跟着的   
$net.targetpath=”http://10.*.*.*”
#为建立的快捷方式建立内容映射,因为是.url,所以映射的是一个网址
$net.save()
#存储快捷方式,不存是不会创建成功的
例:利用COM对象启动一个IE实例
单独运行的COM对象被称做Active X 可执行程序。
$ie=New-object –comobject internetexplorer.application
#利用internetexplorer ProgID即internetexplorer.application建立一个IE实例
#该进程是独立运行的
Get-process
#以上建立的IE实例不可见,但通过进程可以查看到iexplore
$ie.visible=$true
#使IE实例可见
$ie.navigate(“http://www.sohu.com”)
#使用navigate导航到特定网址
$ie.document.body.innertext
#网页中检索文本内容
$ie.quit()
#关闭IE
$ie | get-member
#关闭IE后,该变量失效,可通过get-member检验
$ie=$null
#清除剩余变量的引用
Remove-variable ie
#彻底清除该变量
例:建立非标准的COM对象
New-object –comobject excel.application –strict
#  -strict创建非标准的COM对象
    因为get-member有可选参数 –inputobject,所以$shorcut | get-member可改写为
    get-member –inputobject $shorcut
    注意,-inputobject会将参数视为单独项,所以如果有多个对象存储在变量中,则
-inputobject会把它们当成对象数组。
八.静态类
静态类:不是所有.NET FrameWork类都可以使用new-0bject的,静态类中的属
性和方法是固定的,只可以引用,被能被修改,如System.Environment和System.Math。
因此,new-object system.environment是错误的。
静态类的属性也是静态的,对静态类的静态属性是通过::来引用的。

例:如何查看system.environment的静态属性
[environment] | get-member –static
#注意,有-static和没有-static显示内容是不同的
#有-static则显示system.environment的静态属性
#没有显示system.environment的runtimetype
#[environment] | get-member –membertype property并不能显示静态属性
#之所以写[environment]没有写成[system.environment]是因为system是默认的可省略
例:静态属性的应用
[environment]::osversion

静态类system.math有一些method是相同的,可通过参数区分它们。
[math] | get-member –static –membertype method
例:[math]::sqrt(9)

八.powershell的提供程序和驱动器
提供程序将powershell和驱动器中间的访问数据层抽象化,从而使在统一的机制下与不
同的驱动器进行交互。但实际上,我们并不感觉到提供程序的存在。
Get-help –category provider #获得所有提供程序类型。
用名词PSDrive命名powershell驱动器的名称。
    驱动器分四种:
    filesystem文件系统驱动器:如 C:  D:
    registry注册表驱动器: 如 HKLM: HKLU:
    certificate证书驱动器:如 CER:
Env驱动器(环境变量驱动器):Env:
Variable驱动器(变量驱动器):
    自定义驱动器:条件有三,1。驱动器的名称;2。Psprovider;3。Root既驱动器对应路
径。例 New-PSDRIVE  -name zgktest –psprovider registry –root hklm/software/microsoft/windows/current。进入该驱动器命令 cd zgktest: 或set-location zgktest: -passthru,查看该驱动器下内容命令 dir 。
get-psdrive:获得所有驱动器列表
get-psdrive –psprovider certificate :获得指定的证书驱动器
# -psprovider :就是指定提供程序,记住别落了ps
remove-psdriver –name drivername :删掉指定的驱动器
powershell的驱动器为powershell 自用,用“资源管理器和cmd.exe”是打不开powershell的驱动器的。
powershell退出,新定义的驱动器会消失。可通过export-console 命令将新定义的控制台导出,然后通过参数psconsolefile将其导入到新会话中。
六.        PowerShell的脚本执行策率
powershell的执行策率分四种:Restricted,默认,禁止所有脚本执行;AllSigned,仅运行可信任脚本;RemoteSigned,所有本地脚本可执行,不管它们是否是可信任,如果是从Internet下载的脚本则必须是可信任的;UnRestricted,所有脚本都可以执行。
更改策率命令:set executionpolicy remotesigned,将默认策率由restricted改为remotesigned。
Makecert.exe :制作可信任的安全脚本(微软提供)。
利用makecert.exe制作可信任脚本步骤:
1.创建信任证书:makecert -n "CN=MyRoot" -a sha1 –eku1.3.6.1.5.5.7.3.3 -r -sv root.pvk
root.cer –ss Root -sr localMachine
2.导出信任证书:makecert -pe -n "CN=MyCertificate" -ss MY –a sh1 -eku 1.3.6.1.5.5.7.3.3 –iv
root.pvk –c root.cer
3.用信任证书对脚本进行信任签名:Set-AuthenticodeSignature D:/myscript.ps1 $cert
七.        语法与操作
get-member:获得属性与方法。例:$var1 | get-member 获得$var的属性和方法。$var.[TAB] 用TAB键选择变量的属性和方法。
定向输出:用 “ > ”表示。
注释    :用“ # ”表示。
引号    :注意“单 双”引号的区别。
八.        PowerShell对IIS 的管理
需要iis powershell provider插件的支持。
powershell对IIS7管理更好,对IIS6管理相对较弱,只能做一些start/stop iis 的操作。
常用语法:start-webitem  stop-webitem  get-webitemstate
.创建Web站点
New-Item iis:/Sites/TestSite -bindings
@{protocol="http";bindingInformation=":80:TestSite"} -physicalPath
c:/test
#New-item iis:/Site/TestSite –bindings :新建站点TestSite,并实施绑定
# protocol=”http” 使用http协议
#bindinginfomation=”;80:TestSite” 将80端口映射到站点TestSite
# physicalPath c:/test :站点的物理路径是c:/test
• 创建Web应用程序
New-Item 'IIS:/Sites/Default Web Site/DemoApp' -physicalPath
c:/test -type Application
    #type Application :类型是应用程序
九.        PowerShell如何实行对系统进行管理
重要命令:get-process和stop-process;get-service
例:停止所有无响应的程序
Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process
例:停止所有其它windows powershell对话
Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID} | Stop-Process -
PassThru
例:挂起一个服务spooler
Suspend-service –name spooler
例:重新启动多个服务
Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service
#先获得服务列表,并对它们进行筛选,然后执行重新启动

Get-wmiobject是进行常规系统管理最重要的命令。
例:收集本地计算机桌面相关信息
Get-WmiObject -Class Win32_Desktop -ComputerName .| Select-Object -Property [a-z]*
#wmi类列出的信息很详细,其中还包括“以双下划线表示的wmi元数据”
#可通过select-object进行筛选
#-computername可以省略的,后面的 . 代表本地计算

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

powershell 学习笔记 的相关文章

  • mvn deploy时返回400解决方法.md

    使用mvn deploy命令 将打包后的jar包上传到私服时 出现了下面的问题 Return code is 400 ReasonPhrase Bad Request gt Help 1 一般通用有3个导致出现上面问题的原因 1 pom x

随机推荐

  • 关于IKEv2中安全策略索引SPI的生成

    首先引入一个PF key的概念 PF KEY Key Management API 提供IKE模块和IPSec核心之间的接口 在RFC 2367中 有一个SADB GETSPI消息 这个消息就是实现允许一个进程获取SPI值 该值标识所给的s
  • GTest基础学习-05-第5个单元测试-父test fixture和子test fixture的使用

    这篇来学习Gtest官方示例中的第5个 为什么直接跳过第4个 因为第四个是测试一个简单的计数器 看了下单元测试内容 没有新的知识点 就一个TEST 里面使用了连续3 4个EXPECT TRUE断言宏 完全没有任何新的知识点 就不再介绍第4个
  • html打印,可以控制换页

    显示效果 核心代码 div class pageBreak div 完整代码
  • 计算机网络之域名

    文章目录 计算机网络之域名 1 域名组成 2 域名分类 2 1顶级域名 2 2二级域名 2 3三级域名 2 4顶级域名其他分类 3 中文域名 4 www 计算机网络之域名 1 域名组成 2 域名分类 顶级域名包括顶级域名 二级域名 三级域名
  • docker学习(四)docker run用法

    目录 前言 一 参数列表 二 使用示例 前言 docker run 命令用于创建一个新的容器 启动一个新的进程 并为这个进程分配其独占的文件系统 网络资源等 通过参数设置可以覆盖镜像和容器的一些默认配置 一 参数列表 a 指定标准输入输出内
  • shell的内置命令

    shell有很多内置在其源代码中的命令 这些命令是内置的 所以shell不必到磁盘上搜索它们 执行速度因此加快 bash提供的help功能 能提供任何内置命令的在线帮助 表14 12列出了这些内置命令 表14 12 内置命令 命 令 功 能
  • eclipse常用设置

    eclipse常用设置 设置字体 window preferences General Appearace Colors and Fonts 设置字符编码 window preferences General Workspace Text
  • Spire.XLS 图表系列教程:C# 如何不使用工作数据创建Excel图表以及Excel雷达图

    更多资源查看 Spire XLS工作表教程 Spire Doc系列教程 Spire PDF系列教程 下载Spire XLS最新试用版 Spire XLS for NET 是一款专业的 NET Excel 组件 它可以用在各种 NET 框架中
  • 利用Dialogflow构建聊天机器人

    作者 Priyanka Vergadia Developer Advocate Google Anu Srivastava Developer Advocate AI ML 在如今的办公环境下 在线协同工作至关重要 保持生产力也是关键 聊天
  • 用Python自动化操作PPT,看完这篇文章就够了!

    作者 超级大洋葱806 https tangxing blog csdn net article details 109568830 大家好 我是小z 今天给大家分享一波Python自动化操作PPT的干货 1 PPT自动化能干什么 有什么优
  • django 项目中脚本启动

    django项目中的脚本如何快速方便启动 如上如 创建文件script放置脚本项目文件 在manage py同目录下创建run script py文件启动脚本 run script py代码 coding utf 8 import os i
  • ==与equals有什么区别

    与equals的区别 相同点 1 和equals都是用于完成比较操作 2 和equals的判定结果都是boolean值 true或false 不同点 1 是个运算符 本质上用于比较两个值是否相等 2 使用 运算符比较的值可以是基本类型的值
  • 在ubuntu20.4下安装ROS-noetic(全步骤经反复验证成功)

    注意 如果有conda环境 conda deactivate推出环境 1 4步骤都是很顺利的 如果下载失败请换源 第5步rosdep比较繁琐 但是根据我的使用情况 发现不按照rosdep也能正常使用 更新于2022 3 安装过程的打印信息可
  • 【图像处理】《数字图像处理-冈萨雷斯》笔记

    数字图像处理 冈萨雷斯 笔记 第一章 绪论 图像处理实例 伽马射线成像 X射线成像 紫外波段成像 可见光以及红外线成像 微波波段成像 无线电波成像 声波成像 图像处理的基本步骤 图像获取 滤波与增强 图像复原 彩色图像处理 小波与分辨率处理
  • JMeter 安装教程(详细安装教程)

    JMeter 安装教程 详细安装教程 一 jdk下载 注意 因为jmeter运行依赖jdk环境 所以在安装jmeter之前需要安装jdk且配置环境变量 需要jdk1 8以上版本 1 jdk下载地址 http www oracle com t
  • Vue实现下载及文件重命名

    效果如下 实现步骤 html
  • 理解JavaScript作用域和作用域链

    一 JavaScript中的作用域 作用域是当前的执行上下文 值和表达式在其中 可见 或可被访问 如果一个变量或表达式不在当前的作用域中 那么它是不可用的 function foo var x sfa console log x x is
  • 31黑马QT笔记之QPixmap、QImage、QPicture功能大总结

    31黑马QT笔记之QPixmap QImage QPicture功能大总结 QPixmap QImage既可以用于绘图 又可以作绘图设备时保存图片 而QPicture只能用于作绘图设备时保存图片状态 保存前需要用到前两种方法绘图 要显示必须
  • Go Lang 从Request中解析文件和参数

    如果要处理上传的文件 就必须使用multipart form data编码 处理multipart form data编码的请求时 解析使用ParseMultipartForm 之后从MultipartForm字段取值 前端上传代码
  • powershell 学习笔记

    命令模式 字符串不需要加引号 除变量和圆括号中的内容外的所有内容均可看作字符串 copy users txt accounts txt copy src dest write host 2 2 表达式模式 以最高级别语言分析方法来进行分析