Powershell 3.0 practice (4) develop custom pssnapin

Source: Internet
Author: User
Tags windows x64 windows x86

Powershell uses snapin to provide a scalable architecture for users to add custom features. Snapin is a group of. netProgramSet. To put it bluntly, there are classes.

Any. Net assembly, as long as the installation program class of snapin is implemented, can become a snapin.

Note: powershell 3.0 ctp2 has been released.HereDownload

SinceCtp1The following changes have been made:

  1. Fixed the problem that a large number of usersCtp1. The specific problem list can be found inRelease NotesAnd Connect .
  2. Windows powershell iseTo open a separate command line window.
  3. You can useUpdate-helpTo update the local help. All the help will beInternet.
  4. InWindows powershell workflowsThis release contains a lot of improvements, including:Parallel,SequenceAndInlinescript.
  5. Get-ModuleCurrentlySessionOrCIM sessionObtain the module.

For specific changes, seeWMF ctp2 release notes.docx (Release Notes)

TestCodeDownload

Powershell 3.0 provides the following snapin:

Get-pssnapin

Next we will develop a snapin.

1. I used Visual Studio 11 Developer Preview to create a class library project:

 

2. AddSystem. Management. AutomationReference,System. Management. AutomationYesPowershell SDKTo installPowershell 3.0Has been installed inGAC.

3. InheritancePssnapin
Class, which must be inherited from custom snapin. Name is the name of the custom snapin, verdor is the author, and description is a brief description of the snapin.

 

1 [Runinstaller ( True )]
2 Public class test: pssnapin
3 {
4 // Name For The powershell snap- In .
5 Public override string name
6 {
7 Get
8 {
9 Return " Brooks. scripts. powershell. Test " ;
10 }
11 }
12
13 // Vendor information For The powershell snap- In .
14 Public override string vendor
15 {
16 Get
17 {
18 Return " Brooks " ;
19 }
20 }
21
22 // Description of the powershell snap- In
23 Public override string description
24 {
25 Get
26 {
27 Return " This is a sample powershell snap-in " ;
28 }
29 }
30 }

 

 

4. add your own cmdlet to implement some functions. I want to develop an Excel HELP command to generate an Excel document at a specified position.

To do this, add the reference of office Pia first:Microsoft. Office. InterOP. Excel

 

5. Compile a class inheritance cmdlet. The parameters are represented in the form of attributes and generally need to be rewritten.Beginprocessing (),Processrecord (),Endprocessing ()Three methods.

Beginprocessing (): Perform initialization operations, such as verifying parameters and preparing data.

Processrecord (): Execute the Core Command logic.

Endprocessing (): Finishing work, such as releasing resources and logging.

 

PowershellThe command is
Verb-Term
Structure, here I useNew-ExcelCommand.

Parameter declaration,Mandatory =TrueRequired Parameter,Position = 1
The parameter is a location parameter, so that the parameter can be automatically inferred based on the location.

 

1 [Cmdlet (verbscommon. New, " Excel " )]
2 Public class addtest: cmdlet
3 {
4 Private string _ Path = string. empty;
5 Private excel. xlfileformat _ format = excel. xlfileformat. xlopenxmlworkbook;
6
7 [Parameter (mandatory = True , Position = 1)]
8 Public String path
9 {
10 Get
11 {
12 Return This. _ path;
13 }
14 Set
15 {
16 This. _ Path = value;
17 }
18 }
19
20 [Parameter (mandatory = True , Position = 2)]
21 Public excel. xlfileformat format
22 {
23 Get
24 {
25 Return This. _ format;
26 }
27 Set
28 {
29 This. _ format = value;
30 }
31 }
32
33 Protected override void beginprocessing ()
34 {
35 Base. beginprocessing ();
36 }
37
38 Protected override void processrecord ()
39 {
40 Excel. Application _ APP = new excel. Application ();
41 _ App. displayalerts = False ;
42 Excel. Workbook _ book = _ app. workbooks. Add ();
43 Try
44 {
45 _ Book. saveas (this. path, this. format );
46 }
47 Catch
48 {}
49 Finally
50 {
51 _ App. Quit ();
52 System. runtime. interopservices. Marshal. releasecomobject (_ book );
53 System. runtime. interopservices. Marshal. releasecomobject (_ APP );
54 _ Book = NULL;
55 _ APP = NULL;
56 }
57 }
58
59 Protected override void endprocessing ()
60 {
61 Base. endprocessing ();
62 }
63 }

 

 

6. This snapin is developed. To use it in a script, you need to register the snapin and execute the import.

Run powershell ise as an administrator and run the following script to change the path to your local directory.

Set-location
E: \ work \ project \ brookscom \ Brooks. scripts. powershell \ Brooks. scripts. powershell \ bin \ debug

Set-alias
Installutil
$ ENV: WinDir \ microsoft.net \ framework64 \ v4.0.30319 \ installutil

Installutil
-I
Brooks. scripts. powershell. dll


Installutil is a built-in Installation Tool of. net. The default value is:

% Windir % \ Microsoft. NET \Framework64\ V4.0.30319 --- windows x64

% Windir % \ Microsoft. NET \Framework\ V4.0.30319 --- windows x86

Note that the 64-bit and 32-bit operating systems use the corresponding installutil.

 

Import the snapin as follows:

Add-pssnapin
-Name
Brooks. scripts. powershell. Test

 

Verify whether the import is successful:

Get-pssnapin
-Registered

The custom snapin is located at the following location in the registry:

 

7. Execute the following command: New-Excel

New-Excel
-Path
E: \ test.xlsx
-Format
Xlopenxmlworkbook

We can see that the Excel document is successfully generated:

 

Summary:

Powershell 3.0 contains a large number of commands, which can be used to manage almost all aspects. Especially in Windows Server 8, powershell is already at the core.

The company's CTO is a master of batch processing and compilation, but when I recommended powershell to him, he dismissed it and thought it was too nondescribable. The original saying was "what bird Syntax"J

This also verifies the current situation of powershell and the extent to which it is misunderstood by senior management personnel. This development from a custom snapin demonstrates the scalability of powershell, which is no different from developing a common component. I personally expressed my optimism about the prospect of powershell in enterprise-level management. powershell can also be extended into a script engine embedded into ERP and other systems for deployment, process control, and automated operations.

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.