Powershell创建对象 12


.Net类型中的方法功能很强大。可以通过类型的构造函数创建新的对象,也可以将已存在的对象转换成指定的类型。

通过New-Object创建新对象

如果使用构造函数创建一个指定类型的实例对象,该类型必须至少包含一个签名相匹配的构造函数。例如可以通过字符和数字创建一个包含指定个数字符的字符串:

PS C:Powershell> New-Object String(‘*’,100)
*******************************************************************************
*********************

为什么支持上面的方法,原因是String类中包含一个Void .ctor(Char, Int32) 构造函数

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)

通过类型转换创建对象

通过类型转换可以替代New-Object

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

1999年9月1日 10:23:44

如果条件允许,也可以直接将对象转换成数组

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

加载程序集

自定义一个简单的C#类库编译为Test.dll:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace Test
{
    public class Student
    {
        public string Name { set; get; }
        public int Age { set; get; }
        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);
        }
    }
}

在Powershell中加载这个dll并使用其中的Student类的构造函数生成一个实例,最后调用ToString()方法。

PS C:Powershell> ls .Test.dll

    目录: 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

使用COM对象

作为.NET的补充,Powershell可以加载和访问COM对象。

查看可用的COM对象

每一个COM对象都有存储在注册表中的唯一标识符,想遍历访问可用的COM对象,可是直接访问注册表。

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
......
怎样使用COM对象

一旦得到了COM对象的ProgID,就可以使用New-Object创建COM对象,只需要指定参数为-comObject。

PS C:Powershell> New-Object -ComObject DAO.Relation.36

Properties     : System.__ComObject
Name           :
Table          :
ForeignTable   :
Attributes     : 0
Fields         : System.__ComObject
PartialReplica :

COM对象的和.NET对象相似,任然可是使用Get-Member 得到该对象的所有熟悉和方法:

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}

常用的COM对象中有WScript.Shell,
WScript.Network,
Scripting.FileSystemObject,
InternetExplorer.Application,
Word.Application,
Shell.Application

下面的例子使用WScript.shell COM对象和它的方法CreateShortcut()做桌面上创建一个Powershell快捷方式:

PS C:Powershell> $wshell=New-Object -ComObject WScript.shell
PS C:Powershell> $path=[environment]::GetFolderPath('Desktop')
PS C:Powershell> $link=$wshell.CreateShortcut(“$path/Powershell.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="启动Powershell"
PS C:Powershell> $link.WorkingDirectory=$PROFILE
PS C:Powershell> $link.IconLocation='Powershell.exe'
PS C:Powershell> $link.Save()
本文链接: https://www.pstips.net/powershell-create-new-object.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

12 条评论 “Powershell创建对象

    • Mooser Lee 文章作者
      PS> Get-Process iexplore
      
      Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
      -------  ------    -----      -----     ------     --  -- -----------
          611      50    58012      43984       0.95   9872   1 iexplore
          478      43    19516      38656       0.89  14040   1 iexplore
      
      • anubis

        感谢指导。还有些不太明白:
        New-Object返回的类型是System.__ComObject#{d30c1661-cdaf-11d0-8a3e-00c04fc9e26e}
        Get-Process获得的类型是System.Diagnostics.Process
        它们之间是否有转换的方法,或者说Process的哪个属性里能找到__ComObject?
        举个实例,我手动开一个IE,然后想用Powershell让它导航到www.pstip.net,应该如何操作?

        • Mooser Lee 文章作者

          New-Object返回什么对象,取决于你给他的类型,比如.net 对象,com对象。

          PS> New-Object System.Int32
          0
          PS> New-Object System.Uri http://www.pstips.net/
          
          
          AbsolutePath   : /
          AbsoluteUri    : http://www.pstips.net/
          LocalPath      : /
          Authority      : www.pstips.net
          HostNameType   : Dns
          IsDefaultPort  : True
          IsFile         : False
          IsLoopback     : False
          PathAndQuery   : /
          Segments       : {/}
          IsUnc          : False
          Host           : www.pstips.net
          Port           : 80
          Query          :
          Fragment       :
          Scheme         : http
          OriginalString : http://www.pstips.net/
          DnsSafeHost    : www.pstips.net
          IsAbsoluteUri  : True
          UserEscaped    : False
          UserInfo       :
          
          
          
          PS> New-Object -com "InternetExplorer.Application"
          
          
          Application          : System.__ComObject
          Parent               : System.__ComObject
          Container            :
          Document             :
          TopLevelContainer    : True
          Type                 :
          Left                 : 2400
          Top                  : 340
          Width                : 625
          Height               : 675
          LocationName         :
          LocationURL          :
          Busy                 : False
          Name                 : Internet Explorer
          HWND                 : 7866792
          FullName             : C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE
          Path                 : C:\Program Files (x86)\Internet Explorer\
          Visible              : False
          StatusBar            : False
          StatusText           :
          ToolBar              : 1
          MenuBar              : True
          FullScreen           : False
          ReadyState           : 0
          Offline              : False
          Silent               : False
          RegisterAsBrowser    : False
          RegisterAsDropTarget : True
          TheaterMode          : False
          AddressBar           : True
          

          Get-Process 返回的是进程对象。而你的关注点应当是控制IE,所以是应当选com对象。如果将已打开的IE窗口变成可操作性的com对象,我之前没有研究过。但是你可以先创建IE com对象,再打开你要访问的URL。
          可以参考:PowerShell实现IE Web自动化

          顺便提一下,利用InternetExplorer.Application对象,比较鸡肋,想要使用更丰富的,浏览器UI自动化,还是要使用selenium测试框架:PowerShell Web 测试框架 Selenium

  • 0x6d

    $link=$wshell.CreateShortcut(“$pathPowershell.lnk”) 这段代码少了一个斜杆,导致最后生成的路径不准确
    $link=$wshell.CreateShortcut(“$path/Powershell.lnk”)

  • sisi wu

    PS D:\test_files> $TestDLL=ls .\Test.dll

    PS D:\test_files> $TestDLL

    Directory: D:\test_files

    Mode LastWriteTime Length Name
    —- ————- —— —-
    -a—- 5/31/2019 10:58 AM 500 Test.dll

    PS D:\test_files> [reflection.assembly]::LoadFile($TestDLL.FullName)
    Exception calling “LoadFile” with “1” argument(s): “The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)”
    At line:1 char:1
    + [reflection.assembly]::LoadFile($TestDLL.FullName)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : BadImageFormatException