http://powershell.com/cs/blogs/ebook/default.aspx
数组的使用:
1.在PowerShell中,只要把不同的对象用逗号“,”连接起来,就可以构造出数组对象。
PS C:/> $array1 = 1,2,3,4
PS C:/> $array1.count
4
PS C:/> $array1.GetType().FullName
System.Object[]
PS C:/> $array[0]
1
PS C:/> $a = "My ThinkPad", "My PC"
PS C:/> $a = $a + "My Mac"
PS C:/> $a
My ThinkPad
My PC
My Mac
在PowerShell中,数组其实是一个大小固定的数据结构,如果需要向数组中添加更多的对象时,
就必须使用加号“+”运算符。在执行“+”操作的过程中,PowerShell实际上进行了下述操作:
1) 首先创建一个新的数组,该数组的大小能够存下运算结果的所有对象;
2) 将第一个数组的成员拷贝到新数组中;
3) 将第二个数组的成员拷贝到新数组中。
//
如下说明是翻译: help about_commonparameters 产生的帮助信息.
参数 描述
Verbose 布尔值. 产生操作执行过程更多的细节信息, 有点像跟踪或事务日志. 只有支持生成详细信息的 cmdlet 该参数才有效.
Debug 布尔值. 生成面向程序员处理的详细调式信息. 只有支持生成调式信息的 cmdlet 该参数才有效.
ErrorAction 枚举. 确定错误出现时采取的行动 允许值: Continue [default], Stop, SilentlyContinue, Inquire.
ErrorVariable 字符串. 指定在命令执行过程中产生的错误对象保存的变量名称. $error变量会保存相同的错误对象.
OutVariable 字符串. 指定在命令执行过程中产生的对象保存的变量名称.
OutBuffer 32位整形. 确定执行管道线中下一个命令前, 需要缓存的对象数量.
额外的公共参数, 这两个参数只包含在那些会修改系统信息的 cmdlet 中.
参数 描述
WhatIf 布尔值. 解释执行 cmdlet 将产生的各种操作, 但不会实际执行该命令.
Confirm 布尔值. 执行任何修改系统的操作时, 提示用户, 获得允许后才会执行.
//
Random Numbers in PowerShell
With PowerShell, you can leverage the .NET Framework's System.Random class to create random numbers.
To create a random numbers you must first create a new random number object,
then the object's methods to generate a random number as follows:
$rand = New-Object System.Random
$rand.next()
If you want a random number between 0 and 1, you can use the .NextDouble method which woule look like this:
PSH [D:/foo]: $rand = New-Object system.random
PSH [D:/foo]: $rand.nextdouble()
0.370553521611986
PSH [D:/foo]:$rand.nextdouble()
0.561135980561905
If you want to create random numbers that are between two other numbers
(e.g. a random number between 1 and 10, or between 4 and 16),
you can specify a bottom and top range in a call to .NEXT() as shown here:
PSH [D:/foo]: $rand = New-Object system.random
PSH [D:/foo]: $rand.next(1,10)
7
PSH [D:/foo]: $rand.next(4,16)
14
///
## New-GenericObject.ps1
## Creates an object of a generic type:
##
## Usage:
##
## # Simple generic collection
## $list = New-GenericObject System.Collections.ObjectModel.Collection System.Int32
##
## # Generic dictionary with two types
## New-GenericObject System.Collections.Generic.Dictionary System.String,System.Int32
##
## # Generic list as the second type to a generic dictionary
## $secondType = New-GenericObject System.Collections.Generic.List Int32
## New-GenericObject System.Collections.Generic.Dictionary System.String,$secondType.GetType()
##
## # Generic type with a non-default constructor
## New-GenericObject System.Collections.Generic.LinkedListNode System.Int32 10
##
param(
[string] $typeName = $(throw "Please specify a generic type name"),
[string[]] $typeParameters = $(throw "Please specify the type parameters"),
[object[]] $constructorParameters
)
## Create the generic type name
$genericTypeName = $typeName + '`' + $typeParameters.Count
$genericType = [Type] $genericTypeName
if(-not $genericType)
{
throw "Could not find generic type $genericTypeName"
}
## Bind the type arguments to it
[type[]] $typedParameters = $typeParameters
$closedType = $genericType.MakeGenericType($typedParameters)
if(-not $closedType)
{
throw "Could not make closed type $genericType"
}
,[Activator]::CreateInstance($closedType, $constructorParameters)
/
Saving Data as an XML File
>Get-Process | Export-Clixml c:/scripts/test.xml
Reading in an XML File
>$A = Import-Clixml c:/scripts/test.xml
Arranging Data Into Groups
>Get-Service | Group-Object status
Calculating Basic Statistics
Measure-Object cmdlet provides a way to quickly generate statistics
(count, average, sum, minimum and maximum values)
>Import-Csv c:/scripts/test.txt | Measure-Object score -ave -max -min
>Import-Csv c:/scripts/test.txt | Sort-Object score -descending | Select-Object -first 5
///
Comparing Two Objects or Text Files
>$A = Get-Process
>$B = Get-Process
>Compare-Object $A $B
>$A = Get-Content C:/scripts/x.txt
>$B = Get-Content C:/scripts/y.txt
>Compare-Object $A $B
Displaying Data as a List
the Format-List cmdlet is here to help you display information as a list.
>Get-Service | Format-List
Displaying Data in Multiple Columns
>Get-Process | Format-Wide
>Get-Process | Format-Wide -column 4
>Get-Process | Format-Wide -autosize
Filtering Returned Data
>Get-Process | Where-Object {$_.handles -gt 200}
• -lt -- Less than
• -le -- Less than or equal to
• -gt -- Greater than
• -ge -- Greater than or equal to
• -eq -- Equal to
• -ne -- Not equal to
• -like – Like; uses wildcards for pattern matching
Listing the Unique Members of a Collection
>Get-Content fruits.txt | Sort-Object | Get-Unique
Looping Through a Collection of Objects
>Get-Process | ForEach-Object {Write-Host $_.name -foregroundcolor cyan}
Pausing a Windows PowerShell Script
>Start-Sleep -s 10
>Start-Sleep -m 10000
/
Prompting a User to Enter Information
>$Name = Read-Host "Please enter your name"
>$Password = Read-Host -assecurestring "Please enter your password"
>$a = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
>$b = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($a)
/
Viewing Data One Screen at a Time
>Get-Eventlog PowerShell | Out-Host -paging
>Get-Eventlog PowerShell | Out-Host -p
Writing a Warning Message to the Console Window
>Write-Warning "The folder C:/scripts2 does not exist."
Writing Messages to the Console Window
>Write-Host "This is red text on a yellow background" -foregroundcolor red -backgroundcolor yellow
• Black
• DarkBlue
• DarkGreen
• DarkCyan
• DarkRed
• DarkMagenta
• DarkYellow
• Gray
• DarkGray
• Blue
• Green
• Cyan
• Red
• Magenta
• Yellow
• White
“Dot Sourcing” a Script
#可以看到test.ps1中的变量$c
>. C:/scripts/test.ps1
>$C
$randArray = New-Object byte[] 20
from an earlier post that Bruce answered.
/
[System.Threading.Thread]::GetDomain().GetAssemblies()
Here is an easy way to list all of the fully qualified path names for all assemblies in the GAC
$GacRootDir = Join-Path -Path $Env:SystemRoot -ChildPath "Assembly/Gac"
Get-Childitem -path $GacRootDir -recurse -include *.dll| %{$_.FullName}
# SQL Server to connect to
$sSqlSrv = [string] "SQL2005"
[void][System.Reflection.Assembly]::LoadFile($sPath + "/Microsoft.SqlServer.ConnectionInfo.DLL")
[void][System.Reflection.Assembly]::LoadFile($sPath + "/Microsoft.SqlServer.SMO.DLL")
[void][System.Reflection.Assembly]::LoadFile($sPath + "/Microsoft.SqlServer.SMOEnum.DLL")
$oSrv = New-Object Microsoft.SqlServer.Management.Smo.Server($sSqlSrv)
Write-Host "`r"
Write-Host "Found the following Databases on " $sSqlSrv ":"
Write-Host "`r"
foreach($oDb in $oSrv.Databases)
{
# write database name/ID to console
Write-Host "Database: " $oDb.Name "`t" "DBID " $oDb.ID
}
PowerShell控制台快捷键
按键 | 功能 |
← | 光标向左移动一个字符 |
Ctrl + ← | 光标向左移动一个单词 |
→ | 光标向右移动一个字符 |
Ctrl + → | 光标向右移动一个单词 |
Home键 | 光标移动到行首 |
End键 | 光标移动到行尾 |
Delete键 | 删除光标指向的字符 |
Backspace键或Ctrl + H | 删除光标左边第一个字符 |
Ctrl + End键 | 删除从光标到行尾的所有字符 |
Esc键 | 清除当前输入的所有字符 |
Insert键 | 插入与改写模式切换 |
Tab键 | Tab键自动完成命令,例如:自动完成命令的名称、cmdlet命令的参数、路径。如果第一个提示的对象不是您期望的结果,继续输入Tab键,将会自动显示下一个候选对象。 |
↑ | 向上查询历史命令 |
↓ | 向下查询历史命令 |
F7键 | 显示命令历史记录,以图形列表窗的形式给出所有曾经输入的命令,并可用% D. G0 ?; @9 q! e- }. L/ A* S. q4 A上下箭头键选择再次执行该命令。 |
F8键 | 搜索命令对应的历史记录,在命令上输入命令的一部分内容后,按F8键,可以得到匹配该输入的历史命令。如果有多个匹配项,重复按F8,可以循环显示所有曾经输入的命令。如果命令行为空,则默认匹配所有历史输入的命令。 |
F9键 | 按编号选择历史命令,以图形对话框方式要求您输入命令所对应的编号(从0开始),并将该命令显示在屏幕上。 |
Enter键或Ctrl + M | 回车(Enter) |
Ctrl + C | 终止当前执行的命令 |
Ctrl + Break | 终止当前执行的命令 |
Alt + F7键 | 清除所有曾经输入的命令历史记录 |
# You can compile a class with C# or other .NET languages in PowerShell v2 Add-Type @' public class MyObject { public int MyField = 5; public int xTimesMyField(int x) { return x * MyField; } } '@ $object = New-Object MyObject $object $object.XTimesMyField(10) # You can also use -asCustomObject with the New-Module cmdlet to export a module as a class $object = New-Module { [int]$myField = 5 function XTimesMyField($x) { $x * $myField } Export-ModuleMember -Variable * -Function * } -asCustomObject $object $object.xTimesMyField(10) # You can also simply declare an object and start tacking on properties and methods with the # Add-Member cmdlet. If you use -passThru you can make one giant pipeline that adds all of the # members and assign it to a variable $object = New-Object Object | Add-Member NoteProperty MyField 5 -PassThru | Add-Member ScriptMethod xTimesMyField { param($x) $x * $this.MyField } -PassThru $object $object.xTimesMyField(10)
PS> $foo
Creating a New Object
$pocketknife = New-Object Object
Adding Properties
Next, let's start describing what our object is. To do that, add properties to the object.
# Adding a new property:
Add-Member -MemberType NoteProperty -Name Color -Value Red -InputObject $pocketknife
# Shorten parameter names:
Add-Member -Me NoteProperty -In $pocketknife -Na Weight -Value 55
# Specify arguments without parameter names by position data:
Add-Member -InputObject $pocketknife NoteProperty Manufacturer Idera
Adding Methods
# Adding a new method:
Add-Member -MemberType ScriptMethod -In $pocketknife `
-Name cut -Value { "I'm whittling now" }
# Specify arguments without parameter names by position data:
Add-Member -in $pocketknife ScriptMethod screw { "Phew...it's in!" }
# Specifying "InputObject" directly through the pipeline:
$pocketknife | Add-Member ScriptMethod corkscrew { "Pop! Cheers!" }
Whenever a type is an enumeration, you can use a special .NET method called GetNames() to list the possible values defined in that enumeration:
[System.Enum]::GetNames([System.ConsoleColor])
Standard Methods
In addition, nearly every object contains a number of "inherited" methods that are also not specific to the object but perform general tasks for every object:
Method | Description |
Equals | Verifies whether the object is identical to a comparison object |
GetHashCode | Retrieves an object's digital "fingerprint" |
GetType | Retrieves the underlying object type |
ToString | Converts the object into readable text |
This is how you could use PromptForChoice() to create a simple menu:
$yes = ([System.Management.Automation.Host.ChoiceDescription]"&yes")
$no = ([System.Management.Automation.Host.ChoiceDescription]"&no")
$selection = [System.Management.Automation.Host.ChoiceDescription[]]($yes,$no)
$answer = $host.ui.PromptForChoice('Reboot', 'May the system now be rebooted?',$selection,1)
$selection[$answer]
if ($answer -eq 0) {
"Reboot"
} else {
"OK, then not"
}
Using Object Properties
MemberType | Description |
AliasProperty | Alternative name for a property that already exists |
CodeProperty | Static .NET method returns property contents |
Property | Genuine property |
NoteProperty | Subsequently added property with set data value |
ScriptProperty | Subsequently added property whose value is calculated by a script |
ParameterizedProperty | Property requiring additional arguments |
Using Object Methods
MemberType | Description |
CodeMethod | Method mapped to a static .NET method |
Method | Genuine method |
ScriptMethod | Method invokes PowerShell code |
Listing Assemblies
[AppDomain]::CurrentDomain
[AppDomain]::CurrentDomain.GetAssemblies()
System.Reflection.Assembly type provides methods to manually load additional assemblies
from .NET DLL files or the global assembly cache.
$searchtext = "*Environment*"
[AppDomain]::CurrentDomain.GetAssemblies() |
foreach-object { $_.GetExportedTypes() } |
where-object { $_ -like $searchtext } |
foreach-object { $_.FullName }
$datetime = [System.DateTime] '1.1.2000'
$datetime.GetType().Fullname
System.DateTime$datetime = New-Object System.DateTime
$datetime.GetType().Fullname
System.DateTime$datetime = Get-Date
$datetime.GetType().Fullname
System.DateTime$datetime = [System.DateTime]::Parse('1.1.2000')
$datetime.GetType().Fullname
System.DateTime
Using Constructors
[System.String].GetConstructors() |
ForEach-Object { $_.toString() }
# Use strong typing to set the object type of $date:
[System.DateTime]$date = "November 1, 2007"
# Load required assembly:
[void][reflection.assembly]::LoadWithPartialName("Microsoft.VisualBasic")
Using COM Objects
Which COM Objects Are Available?
Dir REGISTRY::HKEY_CLASSES_ROOT/CLSID -include PROGID -recurse |
foreach {$_.GetValue("")}
How Do You Use COM Objects?
$object = New-Object -ComObject WScript.Shell
# Create an object:
$wshell = New-Object -comObject WScript.Shell
# Assign a path to Desktop to the variable $path
$path = [system.Environment]::GetFolderPath('Desktop')
# Create a link object
$link = $wshell.CreateShortcut("$path/PowerShell.lnk")
# $link is an object and has the properties and methods
$link | Get-Member# We can populate some of the properties
$link.TargetPath = 'powershell.exe'
$link.Description = 'Launch Windows PowerShell console'
$link.WorkingDirectory = $profile
$link.IconLocation = 'powershell.exe'
# And save the changes using Save() method
$link.Save()
PowerShell PowerBoots
http://powerboots.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=22873
To Install in PowerShell 2.0 (CTP3)
- Download one of the PowerBoots files below (PoshWpf is included)
- Unpack into your Modules directory
- Double check: the files should be in, eg: ... Documents/WindowsPowerShell/Modules/PowerBoots
- Run Import-Module PowerBoots from PowerShell or add that to your profile
PowerShell.exe –sta doesn’t load up WPF’s assemblies, lets run these three lines to add the references:
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
也可以这样
PowerShell 编写 WPF 代码的经验总结
- PowerShell 要在 -STA 模式下运行程序。
- 要加载相应的库 PresentationFramework, PresentationCore, WindowsBase. 方法是:Add-Type –assemblyName WindowsBase
- 如果要导入C#代码要加入 -ReferencedAssemblies ("PresentationCore","PresentationFramework","WindowsBase")
- 显示窗口时要用 win.ShowDialog() 而不能用 win.Show() 也不能有 Application 对象。
How To Write a Console Application in PowerShell with Add-Type
using System;
public class MyProgram
{
public static void Main(string[] args) {
Console.WriteLine("Hello World");
}
}
"@
# Load required assembly:
[void][reflection.assembly]::LoadWithPartialName("PresentationFramework")