PowerShell calls a static method

Source: Internet
Author: User
Tags string format

PowerShell stores information in objects, each object has a specific type, and simple text is stored in the System.String type, and dates are stored as System.DateTime types. Any. NET object can return its type through the GetType () method, which has a FullName property that can be used to view the full name of the type.

PS c:powershell> $date =get-dateps c:powershell> $date January 11, 2012 15:19:49ps c:powershell> $date. GetType (). Fullnamesystem.datetime

Each type can contain some static methods, you can get the type object itself by square brackets and type names, and then view all the static methods supported by that type through the Get-memeber command.

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 ... Daysinmonthmethod static int DaysInMonth (int year, int month) Equalsmethod static bool Equals (System.DateTime t1, S Ystem.Dat ... Frombinarymethod static System.DateTime frombinary (long datedata) fromfiletimemethod static System.DateTime FromFil ETime (Long fileTime) fromfiletimeutc Method static System.DateTime fromfiletimeutc (Long filet ... FromOADate method Static System.DateTime fromoadate (double D) Isleapyear method static bool Isleapyear (in T year) parse Method static System.DateTime parse (string s), static Sy ... ParseExact Method static System.DateTime ParseExact (string s, Strin ... Referenceequalesmethod 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 ...

Static methods supported by the System.DateTime class are very useful
Use the Parse method to convert a string into a DateTime class:

PS c:powershell> [System.DateTime]::P arse ("2012-10-13 23:42:55") October 13, 2012 23:42:55

Using the Isleapyear method to determine leap years

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

Another common class is the math class, which defines a number of practical static methods in the Math class:
For example, to find absolute value, trigonometric functions, rounding:

PS c:powershell> [Math]::abs ( -10.89) 10.89PS c:powershell> [Math]::sin ([math]::P i/2) 1PS c:powershell> [math] :: Truncate (2012.7765) 2012
See what's interesting. NET Type

. NET supports thousands of types, with these types you can do a lot of things, fortunately PowerShell just supports these types.

Object Type Conversions

For example, use the System.Net.IPAddress class to convert a string IP address into a IPAddress instance

PS c:powershell> [net.ipaddress] ' 10.3.129.71 ' Address           : 1199637258AddressFamily     : Internetworkscopeid           : Isipv6multicast   : falseisipv6linklocal:falseisipv6sitelocal:falseipaddresstostring:10.3.129.71
Calling a static method

Also is the System.Net.IPAddress class, according to the IP address view hostname, 8.8.8.8 is Google's free DNS server

PS c:powershell> [System.net.dns]::gethostbyaddress (' 8.8.8.8 ') | Flhostname    : google-public-dns-a.google.comaliases     : {}addresslist: {8.8.8.8}
To create an instance from a type

The following shows the download of the file through the DownloadFile method of the $webclient class:

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
To view an assembly

. NET is defined in different assemblies, the first thing to know is that the current program has loaded those assemblies. The AppDomain class can accomplish this requirement because it has a static member in Currentdomain,currentdomain with a getassemblies () method.

PS c:powershell> [Appdomain]::currentdomainfriendlyname:defaultdomainid:1applicationd     Escription:basedirectory:c:windowssystem32windowspowershellv1.0dynamicdirectory:relativesearchpath : SetupInformation:System.AppDomainSetupShadowCopyFiles:FalsePS c:powershell> [Appdomain]::currentdomai N.getassemblies () GAC Version location------------------True v2.0.50727 c:windowsmicrosoft.netf Rameworkv2.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 ...
Search for the specified type

Querying methods in each assembly uses the Getexportedtypes () method. Because many assemblies contain a number of methods, it is a good idea to specify keywords when searching. The following code shows how to find the type that contains the "environment" keyword.

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.EnvironmentPermissionAccessSyst Em. Security.Permissions.EnvironmentPermissionSystem.Security.Permissions.EnvironmentPermissionAttributeMicrosoft.PowerShell . Commands.environmentprovider

One of the types found above is: System.Environment class, System.Environment class can do a lot of things, you can first look at the following System.Environment class of all static methods.

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) Expandenvironmentvariablesmethod static string Expandenvironmentva Riablfailfast method Static System.Void FailFast (String Mesgetcommandlineargs method sta Tic string[] GetCommandLineArgs () getenvironmentvariable Method static string GetEnvironmentVariable (Sgetenvironmen Tvariables method Static System.Collections.IDictionaryGetFolderPath method static string Getfolde     RPath (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 Sy Stem. Int32 ExitCode {get;set; hasshutdownstarted Property Static System.Boolean Hasshutdownstartmachinename property static S Ystem. String machinename {get; NewLine Property Static System.String NewLine {get;} OSVersion Property Static System.operatingsystem Osversioprocessorcount property static S Ystem. Int32 ProcessorCount {gestacktrace property static System.String StackTrace {get;} Systemdirectory Property Static System.String systemdirectory {TickCount property static S Ystem. Int32 TickCount {get;} UserDomainName Property Static System.String UserDomainName {guserinteractive property static S Ystem.   Boolean Userinteractiveusername                Property static System.String UserName {get;} Version Property static system.version version {get;} WorkingSet Property Static System.Int64 WorkingSet {get;}

For example, the properties in system.environment output the current logon domain, user name, machine name:

PS c:powershell> [Environment]::userdomainnamemyhomeps c:powershell> [Environment]::usernamexiaomingps C: powershell> [Environment]::machinenamelocalhost
Search method

The following example shows how to search for a method based on the specified keyword "Address".

[Appdomain]::currentdomain.getassemblies () | Foreach-object {$_. Getexportedtypes ()} | Foreach-object {$_.getmembers ()} | where-object {$_.isstatic} | Where-object {$_-like $searchtext} | foreach-object {"[{0}]::{1} and {2}"-F $_.declaringtype, $_.tostring (). SubString ($_.tostring (). IndexOf ("") +1), $_. ReturnType}[system.net.ipaddress]::P arse (System.String)--system.net.ipaddress[system.net.ipaddress]::i Sloopback (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--&GT [System.Net.Sockets.AddressFamily]::P up-->[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]::D atakit-->[ System.net.sockets.addressfamily]::ccitt-->[system.net.sockets.addressfamily]::sna-->[ System.Net.Sockets.AddressFamily]::D ecnet-->[system.net.sockets.addressfamily]::D atalink-->[ 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]::D estinationaddressrequired-->[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] ::D uplicate-->[system.net.networkinformation.duplicateaddressdetectionstate]::D eprecated-->[ System.Net.NetworkInformation.DuplicateAddressDetectionState]::P referred-->[ 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]::P arse (System.String)-- System.net.networkinformation.physicaladdress[system.net.networkinformation.physicaladdress]::none-->[ System.net.networkinformation.suffixorigin]::linklayeraddress-->[ System.DirectoryServices.ActiveDirectory.ActiveDirectorySyntax]::P resentationaddress-->[ Microsoft.JScript.JSError]::D oesnothaveanaddreSS-->[microsoft.jscript.jserror]::wronguseofaddressof-- 
This article link: http://www.pstips.net/powershell-using-static-methods.html

PowerShell calls a static method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.