Powershell基础:类和对象

对象

Powershell中,我们可以自定义对象。对象的创建和使用方式类似javascript等其他脚本语言

初始化

$myObj=New-Object PSObject -Property ` 
@{
            apple="";
            banana=@();
            orange=@{}
        }

注意`和@如果处于同一行要隔着一个空格,处于不同行则只能隔着回车

调用

$myObj.apple="Newton"
$myObj.banana+=@("Pine")
$myObj.orange+=@{
                "A"=1;
                "B"=2}

添加新成员

可以通过Add-Member添加新的成员

1.变量

Add-Member -InputObject $myObj -Name pear -Value "111" -MemberType NoteProperty
Add-Member -InputObject $myObj -Name lemon -Value @("22","33") -MemberType NoteProperty

InputObject指定对象,MemberType指定要给对象添加的元素类型。NoteObject表示基本的数据类型

2.方法

Add-Member -in $myObj ScriptMethod newFunc{ "This is a function" }

常用对象

Powershell可以和C#无缝衔接,所以许多.net框架中的对象可以直接使用,比如Arraylist以及.net中一些连接数据库的操作等

$arr = New-Object -TypeName System.Collections.ArrayList
$arr = New-Object "System.Collections.ArrayList"

初始化可以根据类名直接使用.net的类库。但要注意的是不是所有.net的对象都支持。

$arr.Add(1)        #添加新元素

使用Arraylist比传统数组的优势在于每次添加新元素不用重新开辟一个新数组赋值。Arraylist的其他相关操作和C#的没有明显区别

在Powershell5.0后,powershell也开始支持像C++一样的类操作。

Class Student
{
    [String]$Name;
    [UInt32]$SID;

    Student([String]$Name,[UInt32]$SID)
    {
        $this.Name=$Name
        $this.SID=$SID
    }

    [String]getSID()
    {
        return $this.SID
    }
}

在成员函数中使用成员变量需要用$this,否则会提示该变量不在作用域

$myClass=[Student]::new("King",223)    #创建对象
$myClass.getSID()                  #调用方法

猜你喜欢

转载自blog.csdn.net/JasonJun128/article/details/81476872