Windows PowerShell Create Objects _powershell

Source: Internet
Author: User
Tags rollback

Create a new object from New-object

If you use a constructor to create an instance object of a specified type, the type must contain at least one constructor that matches the signature. For example, you can create a string that contains a specified number character by using characters and numbers:

Copy Code code as follows:

PS c:powershell> new-object String (' * ', 100)

*******************************************************************************
*********************

Why the above method is supported because the string class contains a void. ctor (Char, Int32) constructor

Copy Code code as follows:

PS c:powershell> [String]. GetConstructors () | foreach {$_.tostring ()}
Void. ctor (char*)
Void. ctor (char*, Int32, Int32)
Void. ctor (sbyte*)
Void. ctor (sbyte*, Int32, Int32)
Void. ctor (sbyte*, Int32, Int32, System.Text.Encoding)
Void. ctor (char[], Int32, Int32)
Void. ctor (char[])
Void. ctor (Char, Int32)

Creating objects from type conversions

New-object can be replaced by type conversions

Copy Code code as follows:

PS c:powershell> $date = "1999-9-1 10:23:44"
PS c:powershell> $date. GetType (). FullName
System.String
PS c:powershell> $date
1999-9-1 10:23:44
PS c:powershell> [DateTime] $date = "1999-9-1 10:23:44"
PS c:powershell> $date. GetType (). FullName
System.DateTime
PS c:powershell> $date

September 1, 1999 10:23:44

You can also convert an object to an array directly if the condition allows

Copy Code code as follows:

PS c:powershell> [char[]] "mossfly.com"
M
O
S
S
F
L
Y
.
C
O
M
PS c:powershell> [int[]][char[]] "mossfly.com"
109
111
115
115
102
108
121
46
99
111
109

Loading an assembly

Custom a simple C # class library compiled to Test.dll:

Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;

Namespace Test
{
public class Student
{
public string Name {set;
public int Age {set;
Public Student (string name, int age)
{
This. name = name;
This. Age = age;
}
public override string ToString ()
{
return string. Format ("name={0}; Age={1} ", this. Name,this. Age);
}
}
}

Load the DLL in PowerShell and use the constructor of the student class in it to generate an instance, and finally call the ToString () method.

Copy Code code as follows:

PS c:powershell> ls. Test.dll

Table of Contents: C:powershell

Mode LastWriteTime Length Name
----                -------------     ------ ----
-A---2012/1/13 10:49 4608 Test.dll

PS c:powershell> $TestDLL =ls. Test.dll
PS c:powershell> [Reflection.assembly]::loadfile ($TestDLL. FullName)

GAC Version Location
---    -------        --------
False v2.0.50727 C:powershelltest.dll

PS c:powershell> $stu =new-object test.student (' Mosser ', 22)
PS c:powershell> $stu

Name Age
----                                                                        ---
Mosser 22

PS c:powershell> $stu. ToString ()
Name=mosser; Age=22

Using COM objects

As. NET, PowerShell can load and access COM objects.

To view available COM objects

Each COM object has a unique identifier stored in the registry and wants to traverse access to the available COM objects, but access the registry directly.

Copy Code code as follows:

Dir Registry::hkey_classes_rootclsid-include Progid-recurse | foreach {$_. GetValue ("")}
DAO. dbengine.36
DAO. privatedbengine.36
DAO. tabledef.36
DAO. field.36
DAO. index.36
PS c:powershell> Dir registry::hkey_classes_rootclsid-include progid-recurse
| foreach {$_. GetValue ("")} | Select-first 10
DAO. dbengine.36
DAO. privatedbengine.36
DAO. tabledef.36
DAO. field.36
DAO. index.36
DAO. group.36
DAO. user.36
DAO. querydef.36
DAO. relation.36
File
......

How to use COM objects

Once you get the ProgID of a COM object, you can use New-object to create a COM object with just the specified parameter as-comobject.

Copy Code code as follows:

PS c:powershell> new-object-comobject DAO. relation.36

Properties:system.__comobject
Name:
Table:
ForeignTable:
attributes:0
Fields:system.__comobject
PartialReplica:
COM objects are similar to. NET objects, but use Get-member to get all the familiarity and methods of the object:

PS c:powershell> $DBEng =new-object-comobject DAO. privatedbengine.36
PS c:powershell> $DBEng | Get-member-me *method

TYPENAME:SYSTEM.__COMOBJECT#{00000021-0000-0010-8000-00AA006D2EA4}

Name MemberType Definition
----                ---------- ----------
BeginTrans method void BeginTrans ()
CommitTrans method void CommitTrans (int)
CompactDatabase method void CompactDatabase (String, String, Variant ...)
CreateDatabase method Database CreateDatabase (String, String, Vari ...)
CreateWorkspace method Workspace CreateWorkspace (String, String, st ...)
Freelocks method void Freelocks ()
Idle method void Idle (Variant)
ISAMStats method int ISAMStats (int, Variant)
OpenConnection method Connection OpenConnection (String, Variant, V ...)
OpenDatabase method Database OpenDatabase (String, Variant, Varia ...)
RegisterDatabase method void RegisterDatabase (String, String, bool, ...)
RepairDatabase method void RepairDatabase (String)
Rollback method void Rollback ()
Setdataaccessoption method void Setdataaccessoption (short, Variant)
Setdefaultworkspace method void Setdefaultworkspace (String, String)
SetOption method void SetOption (int, Variant)
_30_createworkspace method Workspace _30_createworkspace (String, String ...)

PS c:powershell> $DBEng | Get-member-me *property

TYPENAME:SYSTEM.__COMOBJECT#{00000021-0000-0010-8000-00AA006D2EA4}

Name MemberType Definition
----            ---------- ----------
DefaultPassword Property String DefaultPassword () {Set}
DefaultType Property int DefaultType () {get} {set}
DefaultUser Property String DefaultUser () {Set}
Errors Property Errors Errors () {get}
IniPath Property String IniPath () {get} {set}
LoginTimeout Property Short LoginTimeout () {get} {set}
Properties Property Properties-Properties () {get}
SystemDB Property String SystemDB () {get} {set}
Version Property string version () {Get}
Workspaces Property Workspaces Workspaces () {get}

Common COM objects have

Wscript.Shell,
Wscript.Network,
Scripting.FileSystemObject,
Internetexplorer.application,
Word.Application,
Shell.Application

The following example uses the Wscript.Shell COM object and its method CreateShortcut () to create a PowerShell shortcut on the desktop:

Copy Code code as follows:

PS c:powershell> $wshell =new-object-comobject Wscript.Shell
PS c:powershell> $path =[environment]::getfolderpath (' Desktop ')
PS c:powershell> $link = $wshell. CreateShortcut ("$pathPowershell. lnk")
PS c:powershell> $link | Get-member

TYPENAME:SYSTEM.__COMOBJECT#{F935DC23-1CF0-11D0-ADB9-00C04FD58A0B}

Name MemberType Definition
----             ---------- ----------
Load method void Load (String)
Save method Void Save ()
Arguments Property String Arguments () {get} {set}
Description Property String Description () {get} {set}
FullName Property String FullName () {get}
Hotkey Property String Hotkey () {get} {set}
IconLocation Property String IconLocation () {get} {set}
RelativePath Property String RelativePath () {Set}
TargetPath Property String TargetPath () {get} {set}
WindowStyle Property int WindowStyle () {get} {set}
WorkingDirectory Property String WorkingDirectory () {get} {set}

PS c:powershell> $link. Targetpath= ' Powershell.exe '
PS c:powershell> $link. description= "Start PowerShell"
PS c:powershell> $link. workingdirectory= $PROFILE
PS c:powershell> $link. iconlocation= ' Powershell.exe '
PS c:powershell> $link. Save ()

Related Article

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.