PowerShell命令

 

[PowerShell]

#别名
ac = Add-Content
asnp = Add-PSSnapin
clc = Clear-Content
cli = Clear-Item
clp = Clear-ItemProperty
clv = Clear-Variable
cpi = Copy-Item
cpp = Copy-ItemProperty
cvpa = Convert-Path
diff = Compare-Object
epal = Export-Alias
epcsv = Export-Csv
fc = Format-Custom
fl = Format-List
foreach = ForEach-Object
% = ForEach-Object
ft = Format-Table
fw = Format-Wide
gal = Get-Alias
gc = Get-Content
gci = Get-ChildItem
gcm = Get-Command
gdr = Get-PSDrive
ghy = Get-History
gi = Get-Item
gl = Get-Location
gm = Get-Member
gp = Get-ItemProperty
gps = Get-Process
group = Group-Object
gsv = Get-Service
gsnp = Get-PSSnapin
gu = Get-Unique
gv = Get-Variable
gwmi = Get-WmiObject
iex = Invoke-Expression
ihy = Invoke-History
ii = Invoke-Item
ipal = Import-Alias
ipcsv = Import-Csv
mi = Move-Item
mp = Move-ItemProperty
nal = New-Alias
ndr = New-PSDrive
ni = New-Item
nv = New-Variable
oh = Out-Host
rdr = Remove-PSDrive
ri = Remove-Item
rni = Rename-Item
rnp = Rename-ItemProperty
rp = Remove-ItemProperty
rsnp = Remove-PSSnapin
rv = Remove-Variable
rvpa = Resolve-Path
sal = Set-Alias
sasv = Start-Service
sc = Set-Content
select = Select-Object
si = Set-Item
sl = Set-Location
sleep = Start-Sleep
sort = Sort-Object
sp = Set-ItemProperty
spps = Stop-Process
spsv = Stop-Service
sv = Set-Variable
tee = Tee-Object
where = Where-Object
? = Where-Object
write = Write-Output
cat = Get-Content
cd = Set-Location
clear = Clear-Host
cp = Copy-Item
h = Get-History
history = Get-History
kill = Stop-Process
lp = Out-Printer
ls = Get-ChildItem
mount = New-PSDrive
mv = Move-Item
popd = Pop-Location
ps = Get-Process
pushd = Push-Location
pwd = Get-Location
r = Invoke-History
rm = Remove-Item
rmdir = Remove-Item
echo = Write-Output
cls = Clear-Host
chdir = Set-Location
copy = Copy-Item
del = Remove-Item
dir = Get-ChildItem
erase = Remove-Item
move = Move-Item
rd = Remove-Item
ren = Rename-Item
set = Set-Variable
type = Get-Content

#PSDrive
alias
cert
env
function
hkcu
hklm
variable

#获取帮助
help get*
help *process
help dir
help dir -full
help dir -detailed
help dir -example
dir -?

#转义序列
   `0      //空值
   `a      //Beep
   `b      //退格
   `f      //换页
   `n      //新行
   `r      //回车
   `t      //制表符
   `v      //垂直引号
   ``      // "`"

#数字常量

   1kb     // 1024
   1mb
   1gb
   1e3     // 1000
   0xFFFF  // 65535

#编辑脚本,推荐使用PrimalScript的最新版本,非常强大

#设置脚本安全策略
set-executionpolicy Restricted  #默认
set-executionpolicy AllSigned  #部署
set-executionpolicy RemoteSigned #开发
set-executionpolicy Unrestricted #不推荐

#执行脚本必须带路径
./myScript.ps1

#获取基于用户名和密码的凭据对象
$cert = get-credential

#对脚本签名
$cert = Get-PfxCertificate C:\Test\Mysign.pfx
Set-AuthenticodeSignature myScript.ps1 -cert $cert

#操作系统
gwmi win32_operatingsystem

#自动变量
$Args  #传递进函数的参数
$_  #通过管道传入的对象
$input  #通过管道传入的对象集合
$$      #前一命令行的最后一个标记
$?      #上一命令的布尔状态
$^      #前一命令行的第一个标记
$Matches #使用 –match 运算符找到的匹配项的哈希表
$Error[0] #前一次错误
$Home   #用户的主目录
$Host   #引用宿主 POWERSHELL 语言的应用程序
$LastExitCode #上一程序或脚本的退出代码
$PSHome #Windows PowerShell 的安装位置
$profile #标准配置文件(可能不存在)
$StackTrace #Windows PowerShell 捕获的上一异常


#类型
   空类型
       [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)

example:
#[void]
[void] $var #可以阻止$var输出

#[xml]
$var = [xml] "onetwo3"
$var.top
$var.top.a
$var.top.a = "13"

#自定义函数
function writeln([string] $str) { echo $str }
function writeln([string] $str) { Begin {echo "Begin"} Process {echo $str} End {echo "End"} }
function writeln { param ([string] $str = $(throw "missing parameter")); echo $str }
${function:writeln} = { param ([string] $str = $(throw "missing parameter")); echo $str }

#文本文件读写
${C:\test.txt} = "Hello`r`n"
${C:\test.txt} += "-----------------"
$Line1 = ${C:\test.txt}[0]

# $null
$var = $null #删除$var
dir > $null
$null = dir

#Invoke
$method = "ToUpper"
"abc".$method.Invoke()

#布尔值
$true
$false

#where, select等的用法
cd c:\
dir | where {$_.Name -eq "WINDOWS"} | select Length,Name
dir | ? {$_.Name -eq "WINDOWS"}

# 列出字符串对象"str"的所有属性与方法
"str" | gm

#强制类型变量
[Boolean] $condition = 0
[string] $str = "hello"

#数组
$array = 1,2,3,4,5,6,7,8
$array = @(1,2,3,4,5,6,7,8)
$array[-1] #最后一个元素
$array[0..4]
$array[-1..-8] #倒序

#哈希表
$hash = @{"Name"="Icebird"; "Job"="Engineer"}

#如何取得文本的行数
(type C:\test.txt | measure-object).Count

#从控制台读取一行输入
$var = Read-Host

#获取环境变量
$path = $env:Path

#读取注册表
$a = (gp "hklm:\\Software\Microsoft\Windows\CurrentVersion").ProductId

#比较和运算
-like  "file.doc" -like "file.*"
-notlike
-contains 1,2,3 -contains 1
-notcontains
----------------------------------
-eq  = (忽略大小写)
-ieq  = (忽略大小写)
-ceq  = (不忽略大小写)
-ne  !=
-gt  >
-lt  <
-ge  >=
-le  <=
以上操作符也可用于对数组操作:1,2,3,5,3,2 -lt 3
----------------------------------
-and
-or
-not
!  等价于-not
-xor
%  模运算
*  可用于字符串重复: "-" * 80

#位操作
-band
-bor
-bnot
-bxor

#特殊操作
$a = "Hat"
$a -replace "a","o"
$a -is [string]
$a = 1 -as [string]
$b = @(1..5)
"{0:d}" -f (get-date)
"{0:yyyy-MM-dd}" -f (get-date)

#格式化
$a = 123456789.456789
$a.ToString("F4")
"{0:F4}" -f $a
"{0,-20:F4}{1}" -f $a,0
"{0,20:F4}" -f $a
"{0:x}" -f 100000
"{0:X}" -f 100000

#正则表达式
$regex = [regex]"He"
$str = "Hello, Hello"
$isMatch = $str -match $regex
$isMatch = $regex.ismatch($str)
$matches = $regex.matches($str)

#双引号与单引号
$a = 1;
"$a"会输出1
'$a'会输出$a

# & 与 .
.{$var = 1} #看作include
&{$var = 1} #看作call
&"dir"  #意味着函数名之类的可以当作参数传入

#foreach
foreach ($file in dir) { $file.Name }
dir | % { $_.Name }

#for
for ($i = 1; $i -lt 5; $i++) {echo $i}

#while
$i = 0
while ($i -lt 4) { $i++; $i }

#do...while
$i = 10
do {$i--; $i} while ($i -lt 5)

#do...until
$i = 10
do {$i--; $i} until ($i -lt 5)

#if...else[if]
$obj = "Hello"
if ($obj -is [string]) { "ISSTRING" }
if ($obj -is [string]) { "ISSTRING" } else { "ISNOTSTRING" }
if ($obj -is [string]) { "ISSTRING" } elseif ($obj -is [int]) { "ISINTEGER" }

#switch
switch (1,2,3) { 1 {"a"} 2 {"b"} 3 {"c"} default {"?"} }
switch (1) { "a" {"China"} "b" {"Japan"} "c" {"c"} default {"???"} }

#switch -regex
$var = "abcdefg"
switch -regex($var) {
"^\w+$" {echo $_" is a word"}
"^\d+$" {echo $_" is a number"}
"^\s+$" {echo $_" is a space"}
default {echo "?"}
}

#switch -casesensitive
#switch -wildcard
#switch -extract ?怎么用
#switch -file  ?怎么用

#抛出错误&捕获异常
throw "Error"
raised "Exception"


trap
{
  write-host "Error: " $_.Exception.Message
#$_.TargetObject
#$_.CategoryInfo
#$_.FullyQualifiedErrorID
#$_.ErrorDetails
#$_.InvocationInfo
  continue
#break
#return
}

#输出格式化
Format-List
Format-Table
Format-Wide
Format-Custom

dir | format-table -groupby Mode
dir | sort Name -desc
dir | sort Name -desc | select Name,Length,Mode | export-csv C:\dir.csv
dir | sort Name -desc | select Name,Length,Mode | export-clixml C:\dir.csv
dir | convertto-html

#使用.NET的对象
$webclient = New-Object System.Net.WebClient
$webclient.Encoding = [System.Text.Encoding]::UTF8
$url = "http://www.cnblogs.com/rss"
$data = [string]$webclient.downloadstring($url)

#使用COM对象
$spVoice = new-object -com "SAPI.spvoice"
$spVoice.Speak("Hello, I am Icebird.")

 

posted on 2009-12-10 16:32  valin  阅读(4595)  评论(0编辑  收藏  举报