PowerShell学习笔记

Windows PowerShell Blog

 

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"
}

## Create the closed version of the generic type
,[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
//////////////////////////////////////////////////////////////////////////////// 
Creating a byte array - Keith Hill
 
$randArray = New-Object byte[] 20
or
$b = [byte[]](1..255)
Note that the first example isn't exactly well documented.  I picked it up
from an earlier post that Bruce answered.
///////////////////////////////////////////////////////////////////////////////// 
Firstly, lets look at what assemblies are loaded by default.
    [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}

load another assembly
[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
 
///////////////////////////////////////////////////////////////////////////////////
Powershell - 列出SQL 上的database
 
$sPath = [string] "C:/Program Files/Microsoft SQL Server/90/SDK/Assemblies"
# SQL Server to connect to
$sSqlSrv = [string] "SQL2005"
# load the assemblies needed for SQL SMO from the SDK
[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")
# new-up a SQL Server SMO Server object reference
$oSrv = New-Object Microsoft.SqlServer.Management.Smo.Server($sSqlSrv)
# write SQL Version to console + line return
Write-Host $sSqlSrv "runs SQL Server Version " $oSrv.Information.Version
Write-Host "`r"
Write-Host "Found the following Databases on " $sSqlSrv ":"
Write-Host "`r"
# enumerate Databases on this server
foreach($oDb in $oSrv.Databases)
{
 # write database name/ID to console
 Write-Host "Database: " $oDb.Name "`t" "DBID " $oDb.ID
}
/////////////////////////////////////////////////////////////////////////////////////
使用串口 RS232
#加载编译器
[void][reflection.assembly]::LoadWithPartialName("System.IO.Ports")
$com1 = New-Object System.IO.Ports.SerialPort
$com1.BaudRate = 19200     #设置波特率
$com1.RtsEnable = $True
$com1.Open()
$com1.ReadExisting()    #读取缓存
$com1.Close()
////////////////////////////////////////////////////////////////////////////////////
 
 

 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) 


We need to tell PowerShell to parse the line in command mode. To do that we use the call operator '&' like so:
PS> & 'C:/Program Files/Windows NT/Accessories/wordpad.exe'
 
Tip:
If it sees one of the characters below then PowerShell parses in Command mode:
[_aA-zZ] & . /

Note that using the call operator invokes the command in a child scope that gets thrown away when the command (script, function, etc) exits.
PS> $foo
PS> & ./script.ps1
PS> $foo
 
When dotting a script, the script executes in the current scope.
PS> $foo
PS> . C:/Users/Keith/script.ps1
PS> $foo
PowerShell Rocks!

PowerShell 2.0 introduces a proper support for multiline comments as shown below.
<#
This is a multiline comment
in PowerShell 2.0
#>

Creating a New Object

Let's turn our real-life pocketknife into a virtual pocketknife. Using New-Object, PowerShell can generate new objects, even a virtual pocketknife.
First you need a new and empty 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])

Listing All Properties

$host | Get-Member -memberType property

Listing All Methods

$host | Get-Member -memberType Method

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

Table 6.2: Standard methods of a .NET object


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


$object | Get-Member -membertype *property

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

Table 6.3: Different property types

 

 

Using Object Methods

[ System.DateTime] | Get-Member -static -memberType *method

MemberType Description
CodeMethod Method mapped to a static .NET method
Method Genuine method
ScriptMethod Method invokes PowerShell code

Table 6.4: Different types of methods

 

 

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.

EndFinding Interesting Classes (Types)

$searchtext = "*Environment*"
[AppDomain]::CurrentDomain.GetAssemblies() |
foreach-object { $_.GetExportedTypes() } |
where-object { $_ -like $searchtext } |
foreach-object { $_.FullName }



Creating New Objects

$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() }


New Objects by Conversion

# Use strong typing to set the object type of $date:
[System.DateTime]$date = "November 1, 2007"


$value = [ DateTime] "November 1, 2007"

Loading Additional Assemblies: Improved Internet Download

# 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)

  1. Download one of the PowerBoots files below (PoshWpf is included)
  2. Unpack into your Modules directory
  3. Double check: the files should be in, eg: ... Documents/WindowsPowerShell/Modules/PowerBoots
  4. Run Import-Module PowerBoots from PowerShell or add that to your profile 

PowerShell.exe -STA   -----------必须在STA模式下

### Import PoshWpf module
Import-Module PowerBoots

$Window = Window -SizeToContent WidthAndHeight -Content (
    Button -Content "Push Me"
    )
$Window.ShowDialog()


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 代码的经验总结


  1. PowerShell 要在 -STA 模式下运行程序。
  2. 要加载相应的库 PresentationFramework, PresentationCore, WindowsBase. 方法是:Add-Type –assemblyName WindowsBase
  3. 如果要导入C#代码要加入 -ReferencedAssemblies ("PresentationCore","PresentationFramework","WindowsBase")
  4. 显示窗口时要用 win.ShowDialog() 而不能用 win.Show() 也不能有 Application 对象。

How To Write a Console Application in PowerShell with Add-Type


Add-Type -OutputType ConsoleApplication -OutputAssembly HelloWorld.exe @" 
using System; 

public class MyProgram 

    public static void Main(string[] args) { 
        Console.WriteLine("Hello World"); 
    } 

"@

# Load required assembly:
[void][reflection.assembly]::LoadWithPartialName("PresentationFramework")

猜你喜欢

转载自blog.csdn.net/anve/article/details/4664700