首页 > 代码库 > Powershell调用静态方法

Powershell调用静态方法

Powershell将信息存储在对象中,每个对象都会有一个具体的类型,简单的文本会以System.String类型存储,日期会以System.DateTime类型存储。任何.NET对象都可以通过GetType()方法返回它的类型,该类型中有一个FullName属性,可以查看类型的完整名称。

PS C:Powershell> $date=get-datePS C:Powershell> $date2012年1月11日 15:19:49PS C:Powershell> $date.GetType().FullNameSystem.DateTime

每一个类型都 可以包含一些静态的方法,可以通过方括号和类型名称得到类型对象本身,然后通过Get-Memeber命令查看该类型支持的所有静态方法。

PS C:Powershell> [System.DateTime] | Get-Member -static -memberType *Method   TypeName: System.DateTimeName            MemberType Definition----            ---------- ----------Compare         	Method     static int Compare(System.DateTime t1, System.Dat...DaysInMonth	Method     static int DaysInMonth(int year, int month)Equals		Method     static bool Equals(System.DateTime t1, System.Dat...FromBinary	Method     static System.DateTime FromBinary(long dateData)FromFileTime	Method     static System.DateTime FromFileTime(long fileTime)FromFileTimeUtc 	Method     static System.DateTime FromFileTimeUtc(long fileT...FromOADate      	Method     static System.DateTime FromOADate(double d)IsLeapYear      	Method     static bool IsLeapYear(int year)Parse           	Method     static System.DateTime Parse(string s), static Sy...ParseExact      	Method     static System.DateTime ParseExact(string s, strin...ReferenceEquales	Method     static bool ReferenceEquals(System.Object objA, S...SpecifyKind     	Method     static System.DateTime SpecifyKind(System.DateTim...TryParse        	Method     static bool TryParse(string s, System.DateTime&, ...TryParseExact   	Method     static bool TryParseExact(string s, string format...

System.DateTime类支持的静态方法非常实用
使用Parse方法将一个字符串转换成DateTime类:

PS C:Powershell> [System.DateTime]::Parse("2012-10-13 23:42:55")2012年10月13日 23:42:55

使用isLeapYear方法判断闰年

#1988年是闰年吗?[System.DateTime]::IsLeapYear(1988)#打印1988到2000年的所有闰年for($year=1988;$year -le 2000;$year++){    if( [System.DateTime]::IsLeapYear($year) ){$year}}True1988199219962000

另一个常用的类为Math类,在Math类中定义了很多实用的静态方法:
例如求绝对值,三角函数,取整:

PS C:Powershell> [Math]::Abs(-10.89)10.89PS C:Powershell> [Math]::Sin([Math]::PI/2)1PS C:Powershell> [Math]::Truncate(2012.7765)2012

查看感兴趣的.NET类型

.NET支持成千上万的类型,有了这些类型可以做许多事情,幸运的是Powershell恰好支持这些类型。

对象类型转换

例如使用System.Net.IPAddress类将字符串IP地址转换成一个IPAddress实例

PS C:Powershell> [Net.IPAddress]‘10.3.129.71‘Address           	: 1199637258AddressFamily     	: InterNetworkScopeId           	:IsIPv6Multicast   	: FalseIsIPv6LinkLocal	: FalseIsIPv6SiteLocal	: FalseIPAddressToString	: 10.3.129.71
调用静态的方法

同样是System.Net.IPAddress类,根据IP地址查看主机名,8.8.8.8是谷歌的免费DNS服务器

PS C:Powershell> [system.Net.Dns]::GetHostByAddress(‘8.8.8.8‘) | flHostName    : google-public-dns-a.google.comAliases     : {}AddressList : {8.8.8.8}
根据类型创建实例

下面演示通过$webClient类的DownloadFile方法下载文件:

PS C:Powershell> $localName="C:Powershellindex.php"PS C:Powershell> Test-Path $localNameFalsePS C:Powershell> $add="http://www.mossfly.com/index.php"PS C:Powershell> $webClient=New-Object Net.WebClientPS C:Powershell> $webClient.DownloadFile($add,$localName)PS C:Powershell> Test-Path $localNameTrue

查看程序集

.NET中的类型定义在不同的程序集中,首先得知道当前程序已经加载了那些程序集。AppDomain类可以完成这个需求,因为它有一个静态成员CurrentDomain,CurrentDomain中有一个GetAssemblies()方法。

PS C:Powershell> [AppDomain]::CurrentDomainFriendlyName           : DefaultDomainId                     : 1ApplicationDescription :BaseDirectory          : C:WINDOWSsystem32WindowsPowerShellv1.0DynamicDirectory       :RelativeSearchPath     :SetupInformation       : System.AppDomainSetupShadowCopyFiles        : FalsePS C:Powershell> [AppDomain]::CurrentDomain.GetAssemblies()GAC    Version        Location---    -------        --------True   v2.0.50727     C:WindowsMicrosoft.NETFrameworkv2.0.50727mscorlib...True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Cons...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem2.0.0.0__b77a5c561...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.Management.Automat...True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Comm...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.Core3.5.0.0__b77a...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.Configuration.Inst...True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.WSMan.Managemen...True   v2.0.50727     C:WindowsassemblyGAC_32System.Transactions2.0.0.0...True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Comm...True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Comm...True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Secu...True   v2.0           C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Cons...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.Xml2.0.0.0__b77a5...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.Management2.0.0.0...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.DirectoryServices...True   v2.0           C:WindowsassemblyGAC_MSILSystem.Management.Automat...True   v2.0           C:WindowsassemblyGAC_MSILMicrosoft.WSMan.Managemen...True   v2.0.50727     C:WindowsMicrosoft.NETFrameworkv2.0.50727mscorlib...True   v2.0           C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Secu...True   v2.0.50727     C:WindowsassemblyGAC_32System.Data2.0.0.0__b77a5c...True   v2.0           C:WindowsassemblyGAC_MSILMicrosoft.PowerShell.Comm...True   v2.0.50727     C:WindowsassemblyGAC_MSILSystem.Configuration2.0....True   v2.0.50727     C:WindowsassemblyGAC_MSILMicrosoft.JScript8.0.0.0...
搜索指定类型

查询每个程序集中的方法可是使用GetExportedTypes() 方法。因为许多程序集中包含了大量的方法,在搜索时最好指定关键字。下面的代码演示如何查找包含”environment”关键字的类型。

PS C:Powershell>  [AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object { $_.GetExportedTypes() } | Where-Object { $_ -like $searchtext } | ForEach-Object { $_.FullName }System.EnvironmentVariableTargetSystem.EnvironmentSystem.Environment+SpecialFolderSystem.Runtime.InteropServices.RuntimeEnvironmentSystem.Security.Permissions.EnvironmentPermissionAccessSystem.Security.Permissions.EnvironmentPermissionSystem.Security.Permissions.EnvironmentPermissionAttributeMicrosoft.PowerShell.Commands.EnvironmentProvider

上面搜索到的类型有一个为:System.Environment类,System.Environment类可以做很多事情,可以先查看以下System.Environment类的所有静态方法。

PS C:Powershell> [Environment] | Get-Member -Static   TypeName: System.EnvironmentName                       	MemberType Definition----                       		---------- ----------Equals                     		Method     static bool Equals(System.Object objA,Exit                       		Method     static System.Void Exit(int exitCode)ExpandEnvironmentVariables	Method     static string ExpandEnvironmentVariablFailFast                   		Method     static System.Void FailFast(string mesGetCommandLineArgs         	Method     static string[] GetCommandLineArgs()GetEnvironmentVariable     	Method     static string GetEnvironmentVariable(sGetEnvironmentVariables    	Method     static System.Collections.IDictionaryGetFolderPath              	Method     static string GetFolderPath(System.EnvGetLogicalDrives           	Method     static string[] GetLogicalDrives()ReferenceEquals            	Method     static bool ReferenceEquals(System.ObjSetEnvironmentVariable     	Method     static System.Void SetEnvironmentVariaCommandLine                	Property   static System.String CommandLine {get;CurrentDirectory           	Property   static System.String CurrentDirectoryExitCode                   	Property   static System.Int32 ExitCode {get;set;HasShutdownStarted         	Property   static System.Boolean HasShutdownStartMachineName                	Property   static System.String MachineName {get;NewLine                    	Property   static System.String NewLine {get;}OSVersion                  	Property   static System.OperatingSystem OSVersioProcessorCount             	Property   static System.Int32 ProcessorCount {geStackTrace                 	Property   static System.String StackTrace {get;}SystemDirectory            	Property   static System.String SystemDirectory {TickCount                  	Property   static System.Int32 TickCount {get;}UserDomainName             	Property   static System.String UserDomainName {gUserInteractive            	Property   static System.Boolean UserInteractiveUserName                   	Property   static System.String UserName {get;}Version                    		Property   static System.Version Version {get;}WorkingSet                 	Property   static System.Int64 WorkingSet {get;}

例如System.Environment中的属性输出当前登录域、用户名、机器名:

PS C:Powershell> [Environment]::UserDomainNameMyHomePS C:Powershell> [Environment]::UserNamexiaomingPS C:Powershell> [Environment]::MachineNameLocalHost
搜索方法

下面的例子演示如何根据指定关键字”Address”,搜索方法。

[AppDomain]::CurrentDomain.GetAssemblies() | ForEach-Object { $_.GetExportedTypes() } | ForEach-Object { $_.getmembers() } | Where-Object { $_.isStatic} | Where-Object { $_ -like $searchtext } | ForEach-Object { "[{0}]::{1} --> {2}" -f  $_.declaringtype, $_.toString().SubString($_.toString().IndexOf(" ")+1), $_.ReturnType }[System.Net.IPAddress]::Parse(System.String) --> System.Net.IPAddress[System.Net.IPAddress]::IsLoopback(System.Net.IPAddress) --> System.Boolean[System.Net.IPAddress]::Any -->[System.Net.IPAddress]::Loopback -->[System.Net.IPAddress]::Broadcast -->[System.Net.IPAddress]::None -->[System.Net.IPAddress]::IPv6Any -->[System.Net.IPAddress]::IPv6Loopback -->[System.Net.IPAddress]::IPv6None -->[System.Net.Sockets.AddressFamily]::Unknown -->[System.Net.Sockets.AddressFamily]::Unspecified -->[System.Net.Sockets.AddressFamily]::Unix -->[System.Net.Sockets.AddressFamily]::InterNetwork -->[System.Net.Sockets.AddressFamily]::ImpLink -->[System.Net.Sockets.AddressFamily]::Pup -->[System.Net.Sockets.AddressFamily]::Chaos -->[System.Net.Sockets.AddressFamily]::NS -->[System.Net.Sockets.AddressFamily]::Ipx -->[System.Net.Sockets.AddressFamily]::Iso -->[System.Net.Sockets.AddressFamily]::Osi -->[System.Net.Sockets.AddressFamily]::Ecma -->[System.Net.Sockets.AddressFamily]::DataKit -->[System.Net.Sockets.AddressFamily]::Ccitt -->[System.Net.Sockets.AddressFamily]::Sna -->[System.Net.Sockets.AddressFamily]::DecNet -->[System.Net.Sockets.AddressFamily]::DataLink -->[System.Net.Sockets.AddressFamily]::Lat -->[System.Net.Sockets.AddressFamily]::HyperChannel -->[System.Net.Sockets.AddressFamily]::AppleTalk -->[System.Net.Sockets.AddressFamily]::NetBios -->[System.Net.Sockets.AddressFamily]::VoiceView -->[System.Net.Sockets.AddressFamily]::FireFox -->[System.Net.Sockets.AddressFamily]::Banyan -->[System.Net.Sockets.AddressFamily]::Atm -->[System.Net.Sockets.AddressFamily]::InterNetworkV6 -->[System.Net.Sockets.AddressFamily]::Cluster -->[System.Net.Sockets.AddressFamily]::Ieee12844 -->[System.Net.Sockets.AddressFamily]::Irda -->[System.Net.Sockets.AddressFamily]::NetworkDesigners -->[System.Net.Sockets.AddressFamily]::Max -->[System.Net.Sockets.IOControlCode]::GetBroadcastAddress -->[System.Net.Sockets.IOControlCode]::AddressListQuery -->[System.Net.Sockets.IOControlCode]::AddressListChange -->[System.Net.Sockets.IOControlCode]::AddressListSort -->[System.Net.Sockets.SocketError]::DestinationAddressRequired -->[System.Net.Sockets.SocketError]::AddressFamilyNotSupported -->[System.Net.Sockets.SocketError]::AddressAlreadyInUse -->[System.Net.Sockets.SocketError]::AddressNotAvailable -->[System.Net.Sockets.SocketOptionName]::ReuseAddress -->[System.Net.Sockets.SocketOptionName]::ExclusiveAddressUse -->[System.Net.NetworkInformation.DuplicateAddressDetectionState]::Invalid -->[System.Net.NetworkInformation.DuplicateAddressDetectionState]::Tentative -->[System.Net.NetworkInformation.DuplicateAddressDetectionState]::Duplicate -->[System.Net.NetworkInformation.DuplicateAddressDetectionState]::Deprecated -->[System.Net.NetworkInformation.DuplicateAddressDetectionState]::Preferred -->[System.Net.NetworkInformation.NetworkChange]::add_NetworkAddressChanged(System.Net.NetworkInformation.NetworkAddressChangedEventHandler) --> System.Void[System.Net.NetworkInformation.NetworkChange]::remove_NetworkAddressChanged(System.Net.NetworkInformation.NetworkAddressChangedEventHandler) --> System.Void[System.Net.NetworkInformation.PhysicalAddress]::Parse(System.String) --> System.Net.NetworkInformation.PhysicalAddress[System.Net.NetworkInformation.PhysicalAddress]::None -->[System.Net.NetworkInformation.SuffixOrigin]::LinkLayerAddress -->[System.DirectoryServices.ActiveDirectory.ActiveDirectorySyntax]::PresentationAddress -->[Microsoft.JScript.JSError]::DoesNotHaveAnAddress -->[Microsoft.JScript.JSError]::WrongUseOfAddressOf -->
本文链接: http://www.pstips.net/powershell-using-static-methods.html

Powershell调用静态方法