Powershell创建对象

.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("$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="启动Powershell"
PS C:Powershell> $link.WorkingDirectory=$PROFILE
PS C:Powershell> $link.IconLocation='Powershell.exe'
PS C:Powershell> $link.Save()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
此资源包含三部分: 1、jxse-shell-2.5.zip 2、jxse-shell-doc-2.5.tar.tar 3、jxse-shell-src-2.5.tar.tar ===附上linux下使用jxtashell的说明=== (windows用户参加jxse-shell-src-2.5/win32/Jxta_Readme.html说明) Linux具体步骤如下: leekwen@leekwen:~$ unzip jxse-shell-2.5.zip leekwen@leekwen:~$ cd jxse-shell-2.5/ leekwen@leekwen:~/jxse-shell-2.5$ ls lib shell leekwen@leekwen:~/jxse-shell-2.5$ cd shell/ leekwen@leekwen:~/jxse-shell-2.5/shell$ ls jxta.exe Jxta_Readme.html run.bat runjdk.bat run.sh leekwen@leekwen:~/jxse-shell-2.5/shell$ chmod a+x run.sh leekwen@leekwen:~/jxse-shell-2.5/shell$ ./run.sh ........ ============================================= =======<[ Welcome to the JXTA Shell ]>======= ============================================= ........ JXTA> man The following commands are available: Shell JXTA Shell command interpreter cat Concatenate and display a Shell object chpgrp Change the current peer group clear Clear the shell's screen dumpcm Dump the content of the local cache (CM) env Display environment variables exit Exit the Shell exportfile Export enviroment variable to an external file flush flush a jxta advertisement get Get data from a pipe message grep Search for matching patterns groups Discover peer groups help To access help pages use the 'man' command. history No description available for this ShellApp importfile Import an external file info display info about an jxta advertisement instjar Installs jar-files containing additional Shell commands join Instantiate and join peer group leave Resign from and optionally stop a peer group logging Display and optionally adjust logging levels login Authenticate with the group's membership service. man An on-line help command that displays information about a specific Shell command mem Display memory information mkadv Make an advertisement from a document mkmsg Make a pipe message mkpipe Create a pipe more Page through a Shell object or from standard input. newmoduleclass Create a new Module Class advertisment newmodulespec Create a new Module Class advertisment newpgrp Create a new peer group advertisement newpipe Create a new pipe advertisment peerconfig Force Peer Reconfiguration peerinfo Get information about peers peers Discover peers pse.certs Display the certificates contained in the current group's PSE Membership pse.createkey Creates a key in the PSE key store pse.dumpcred Dumps a credential. pse.dupkey Creates a key in the PSE key store pse.erase Erases a key or certificate from the PSE key store pse.importcert Imports a trusted certificate chain. pse.keys Display the keys contained in the current group's PSE Membership pse.newcsr Generates certificate signing request document. pse.signcsr Signs a certificate signing request pse.status Display status infomation for the group's PSE Membership publish Publish a JXTA advertisement put Put data into a message rdvcontrol Controls rendezvous service behaviour rdvserver No description available for this ShellApp rdvstatus Display information about the rendezvous service recv Receive a message from a pipe relaystatus Display the list of relays and clients connected to this peer. remotepublish remote publish a jxta advertisement route Display information about a peer's route info rsh Connects to a remote JXTA Shell rshd Remote JXTA Shell Deamon search Discover jxta advertisements send Send a message into a pipe set Set an environment variable sftp Send a file to another peer share Share an advertisement sleep Sleep for a specified amount of milliseconds storehome Display the location of store home talk Talk to another peer transports Display information about the message transports available in the current group uninstjar Uninstalls jar-files previously installed with 'instjar' unset Removes an environment variable version Display the version number of this Shell instance. wc Count the number of lines, words, and chars in an object who Display credential information whoami Display information about this peer or the current peergroup xfer Send a file to another peer

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值