终于把Object有关的看完了。下面将是script的syntax。再然后是一些更advanced的topic。不过明天我就要happy去了。等回来咱们再一起学习。今天头还问我夏天什么打算,她还觉得我干的挺好,生怕夏天就走人了,唉,在SQL Server的时候比这忙多了,也不见什么人说声好。vendor和全职的区别呀。
8. Creating a New Object
Using New-Object
New_Object will call the proper constructor to create the object.
Get list of constructors for a type/class:
[System.String].GetConstructors() | ForEach-Object { $_.toString() }
You can create an object on the fly:
- First you need a new and empty object: $pocketknife = New-Object Object
- # Adding a new property: describe the object
Add-Member -memberType NoteProperty -name Color -valueRed -inputObject $pocketknife
- Adding Methods: define actions that the objectcan take
Add-Member -memberTypeScriptMethod -In $pocketknife -name cut -Value { “I’m whittling now”}
Tricks:
- Specify arguments without parameter names by position data:
Most PowerShell cmdlets canreceive their input objects either by parameter (-inputObject) or via thepipeline, so you can add properties to your object in yet another way:
Add-Member -inputObject$pocketknife NoteProperty Manufacturer Idera
Add-Member -in $pocketknifeScriptMethod screw { “Phew…it’s in!” }
- Specify “inputObject” through the pipeline:
$pocketknife | Add-MemberNoteProperty Blades 3
$pocketknife | Add-MemberScriptMethod corkscrew { “Pop! Cheers!” }
To use any of the methods, add a dot and then the method name followed by two parentheses,which are what distinguish properties from methods.
$objname.methodName()
Without (), it will list the description of methodName.
Type conversion
[System.DateTime]$date = “November1, 2007”
This willconvert String(default type) to DateTime.
Query object
Object property
Object type
MemberType | Description |
AliasProperty | Alternative name for a property that already exists |
CodeProperty | Static .NET method returns property contents, such as get_ method |
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 |
List all properties
- $host | Get-Member -memberType property
- $host.ui.RawUI | Get-Member -memberType Property
List Enum values:
- [System.Enum]::GetNames([System.ConsoleColor])
Object method
Method type
MemberType | Description |
CodeMethod | Method mapped to a static .NET method |
Method | Genuine method |
ScriptMethod | Method invokes PowerShell code |
List all method
$object | Get-Member -memberType *method
List static methods
[System.DateTime] | Get-Member -static -memberType *method
Several Method “Signatures”
Some methods accept different argument types or evendifferent numbers of arguments. To find out which “signatures” a methodsupports, use Get-Member again and look at the Definition property:
$info = $host.UI | Get-MemberWriteLine
$info.Definition
Every single PowerShell command returns objects. Storethe result in variable for easy access later.
Using method
Static method
[object type]::methodname()
For example:
- [System.DateTime]::get_Now()
- [System.DateTime]::Now
- [System.DateTime]::isLeapYear(2010)
- [Math]::Sqrt(64)
Operator
If a method begins with “op_”, it’s an operator, you can usethe method name or use corresponding operator:
Operator method | Cooresponding operator |
op_Addition | + |
op_Subtraction | – |
op_LessThanOrEqual | -le |
op_LessThan | -lt |
op_Inequality | -eq |
op_GreaterThanOrEqual | -ge |
op_GreaterThan | -gt |
Dynamic object instance members
$objName.method(paralist)
Example:
#Download address of a file:
$address = “http://powershell.com/cs/media/p/467/download.aspx”
#Save the file to this location:
$target = “$home\chart_drive_space.V2.ps1”
#Carry out download:
$object = New-Object Net.WebClient
$object.DownloadFile($address, $target)
“Filewas downloaded!”
List asymblies to search forinteresting types
Current application domain
[AppDomain]::CurrentDomain
Find intresting classes/types
$searchtext = “*Environment*”
[AppDomain]::CurrentDomain.GetAssemblies() |
ForEach-Object { $_.GetExportedTypes() } |
Where-Object { $_ -like $searchtext } |
ForEach-Object { $_.FullName }
Load more assembly
[void][reflection.assembly]::LoadWithPartialName(“Microsoft.VisualBasic”)
Using COM object
What are available?
Dir REGISTRY::HKEY_CLASSES_ROOT\CLSID -include PROGID -recurse |
foreach {$_.GetValue(“”)}
COM object issimilar to .Net object. It has properties and methods.
Following examplecreate a shortcut on Desktop:
# 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 propertiesand methods
$link.TargetPath = ‘powershell.exe’
$link.Description = ‘LaunchWindows PowerShell console’
$link.WorkingDirectory = $profile
$link.IconLocation = ‘powershell.exe’
# And save the changes using Save() method
$link.Save()