HowtoCreateanObjectinPowerShell#YoucancompileaclasswithC#orother.NETlanguagesinPowerShellv2
Add-Type@'
publicclassMyObject
{
publicintMyField=5;
publicintxTimesMyField(intx){
returnx*MyField;
}
}
'@
$object=New-ObjectMyObject
$object
$object.XTimesMyField(10)
#Youcanalsouse-asCustomObjectwiththeNew-Modulecmdlettoexportamoduleasaclass
$object=New-Module{
[int]$myField=5
functionXTimesMyField($x){
$x*$myField
}
Export-ModuleMember-Variable*-Function*
}-asCustomObject
$object
$object.xTimesMyField(10)
#Youcanalsosimplydeclareanobjectandstarttackingonpropertiesandmethodswiththe
#Add-Membercmdlet.Ifyouuse-passThruyoucanmakeonegiantpipelinethataddsallofthe
#membersandassignittoavariable
$object=New-ObjectObject|
Add-MemberNotePropertyMyField5-PassThru|
Add-MemberScriptMethodxTimesMyField{
param($x)
$x*$this.MyField
}-PassThru
$object
$object.xTimesMyField(10)
WeneedtotellPowerShelltoparsethelineincommandmode.Todothatweusethecalloperator'&'likeso:PS>&'C:/ProgramFiles/WindowsNT/Accessories/wordpad.exe'Tip:IfitseesoneofthecharactersbelowthenPowerShellparsesinCommandmode:[_aA-zZ]&./Notethatusingthecalloperatorinvokesthecommandinachildscopethatgetsthrownawaywhenthecommand(script,function,etc)exits.PS>$fooPS>&./script.ps1PS>$fooWhendottingascript,thescriptexecutesinthecurrentscope.PS>$fooPS>.C:/Users/Keith/script.ps1PS>$fooPowerShellRocks!PowerShell2.0introducesapropersupportformultilinecommentsasshownbelow.<#ThisisamultilinecommentinPowerShell2.0#>CreatingaNewObject
Let'sturnourreal-lifepocketknifeintoavirtualpocketknife.UsingNew-Object,PowerShellcangeneratenewobjects,evenavirtualpocketknife.Firstyouneedanewandemptyobject:$pocketknife=New-ObjectObject
AddingProperties
Next,let'sstartdescribingwhatourobjectis.Todothat,addpropertiestotheobject.[code]#Addinganewproperty:Add-Member-MemberTypeNoteProperty-NameColor-ValueRed-InputObject$pocketknife
[/code]#Shortenparameternames:Add-Member-MeNoteProperty-In$pocketknife-NaWeight-Value55
#Specifyargumentswithoutparameternamesbypositiondata:Add-Member-InputObject$pocketknifeNotePropertyManufacturerIdera
AddingMethods
#Addinganewmethod:Add-Member-MemberTypeScriptMethod-In$pocketknife`-Namecut-Value{"I'mwhittlingnow"}#Specifyargumentswithoutparameternamesbypositiondata:Add-Member-in$pocketknifeScriptMethodscrew{"Phew...it'sin!"}#Specifying"InputObject"directlythroughthepipeline:$pocketknife|Add-MemberScriptMethodcorkscrew{"Pop!Cheers!"}
Wheneveratypeisanenumeration,youcanuseaspecial.NETmethodcalledGetNames()tolistthepossiblevaluesdefinedinthatenumeration:[System.Enum]::GetNames([System.ConsoleColor])
ListingAllProperties
$host|Get-Member-memberTypepropertyListingAllMethods
$host|Get-Member-memberTypeMethod
StandardMethods
Inaddition,nearlyeveryobjectcontainsanumberof"inherited"methodsthatarealsonotspecifictotheobjectbutperformgeneraltasksforeveryobject:Method | Description |
Equals | Verifieswhethertheobjectisidenticaltoacomparisonobject |
GetHashCode | Retrievesanobject'sdigital"fingerprint" |
GetType | Retrievestheunderlyingobjecttype |
ToString | Convertstheobjectintoreadabletext |
Table6.2:Standardmethodsofa.NETobjectThisishowyoucouldusePromptForChoice()tocreateasimplemenu:$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','Maythesystemnowberebooted?',$selection,1)$selection[$answer]if($answer-eq0){"Reboot"}else{"OK,thennot"}
UsingObjectProperties$object|Get-Member-membertype*propertyMemberType | Description |
AliasProperty | Alternativenameforapropertythatalreadyexists |
CodeProperty | Static.NETmethodreturnspropertycontents |
Property | Genuineproperty |
NoteProperty | Subsequentlyaddedpropertywithsetdatavalue |
ScriptProperty | Subsequentlyaddedpropertywhosevalueiscalculatedbyascript |
ParameterizedProperty | Propertyrequiringadditionalarguments |
Table6.3:DifferentpropertytypesUsingObjectMethods
[System.DateTime]|Get-Member-static-memberType*methodMemberType | Description |
CodeMethod | Methodmappedtoastatic.NETmethod |
Method | Genuinemethod |
ScriptMethod | MethodinvokesPowerShellcode |
Table6.4:DifferenttypesofmethodsListingAssemblies
[AppDomain]::CurrentDomain
[AppDomain]::CurrentDomain.GetAssemblies()
System.Reflection.Assemblytypeprovidesmethodstomanuallyloadadditionalassemblies
from.NETDLLfilesortheglobalassemblycache.
EndFindingInterestingClasses(Types)
$searchtext="*Environment*"[AppDomain]::CurrentDomain.GetAssemblies()|foreach-object{$_.GetExportedTypes()}|where-object{$_-like$searchtext}|foreach-object{$_.FullName}CreatingNewObjects
$datetime=[System.DateTime]'1.1.2000'$datetime.GetType().FullnameSystem.DateTime$datetime=New-ObjectSystem.DateTime$datetime.GetType().FullnameSystem.DateTime$datetime=Get-Date$datetime.GetType().FullnameSystem.DateTime$datetime=[System.DateTime]::Parse('1.1.2000')$datetime.GetType().FullnameSystem.DateTime
UsingConstructors
[System.String].GetConstructors()|ForEach-Object{$_.toString()}NewObjectsbyConversion
#Usestrongtypingtosettheobjecttypeof$date:[System.DateTime]$date="November1,2007"$value=[DateTime]"November1,2007"LoadingAdditionalAssemblies:ImprovedInternetDownload
#Loadrequiredassembly:[void][reflection.assembly]::LoadWithPartialName("Microsoft.VisualBasic")
UsingCOMObjects
WhichCOMObjectsAreAvailable?
DirREGISTRY::HKEY_CLASSES_ROOT/CLSID-includePROGID-recurse|foreach{$_.GetValue("")}
HowDoYouUseCOMObjects?
$object=New-Object-ComObjectWScript.Shell
#Createanobject:$wshell=New-Object-comObjectWScript.Shell#AssignapathtoDesktoptothevariable$path$path=[system.Environment]::GetFolderPath('Desktop')#Createalinkobject$link=$wshell.CreateShortcut("$path/PowerShell.lnk")#$linkisanobjectandhasthepropertiesandmethods$link|Get-Member
#Wecanpopulatesomeoftheproperties$link.TargetPath='powershell.exe'$link.Description='LaunchWindowsPowerShellconsole'$link.WorkingDirectory=$profile$link.IconLocation='powershell.exe'#AndsavethechangesusingSave()method$link.Save()
[/code]PowerShellPowerBoots
http://powerboots.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=22873
ToInstallinPowerShell2.0(CTP3)
DownloadoneofthePowerBootsfilesbelow(PoshWpfisincluded)UnpackintoyourModulesdirectoryDoublecheck:thefilesshouldbein,eg:...Documents/WindowsPowerShell/Modules/PowerBootsRunImport-ModulePowerBootsfromPowerShelloraddthattoyourprofilePowerShell.exe-STA-----------必须在STA模式下###ImportPoshWpfmoduleImport-ModulePowerBoots$Window=Window-SizeToContentWidthAndHeight-Content(Button-Content"PushMe")$Window.ShowDialog()PowerShell.exe–stadoesn’tloadupWPF’sassemblies,letsrunthesethreelinestoaddthereferences:Add-Type–assemblyNamePresentationFrameworkAdd-Type–assemblyNamePresentationCoreAdd-Type–assemblyNameWindowsBase也可以这样PowerShell编写WPF代码的经验总结PowerShell要在-STA模式下运行程序。要加载相应的库PresentationFramework,PresentationCore,WindowsBase.方法是:Add-Type–assemblyNameWindowsBase如果要导入C#代码要加入-ReferencedAssemblies("PresentationCore","PresentationFramework","WindowsBase")显示窗口时要用win.ShowDialog()而不能用win.Show()也不能有Application对象。HowToWriteaConsoleApplicationinPowerShellwithAdd-TypeAdd-Type-OutputTypeConsoleApplication-OutputAssemblyHelloWorld.exe@"usingSystem;publicclassMyProgram{publicstaticvoidMain(string[]args){Console.WriteLine("HelloWorld");}}"@#Loadrequiredassembly:[void][reflection.assembly]::LoadWithPartialName("PresentationFramework")