如何正确重载PowerShell中的方法

时间:2017-11-07 16:39:47

标签: powershell methods overloading

我有一个User Class,它有一个重载方法“SetPassword”,用于填充用户凭据:

class User
{
    ...
    [PSCredential] $Credential
    ...
    SetPassword([string] $Password){
        $UserPassword = ConvertTo-SecureString $Password -AsPlainText -Force
        $UserCredential = New-Object System.Management.Automation.PSCredential (
                $this.name, $UserPassword)
        $this.Credential = $UserCredential
    }

    SetPassword(){
        $Password = Read-Host "Please Enter Password"
        $UserPassword = ConvertTo-SecureString $Password -AsPlainText -Force
        $UserCredential = New-Object System.Management.Automation.PSCredential (
                $this.name, $UserPassword)
        $this.Credential = $UserCredential
    }

我想将这两种方法合并为一种,将$ Password视为可选参数。我会传入密码进行测试,否则会提示用户提供凭据。

PowerShell不允许在方法体中使用PARAM()。

有没有更好的方法来执行此操作,因为我没有重复的代码?

1 个答案:

答案 0 :(得分:3)

调用之前的最具体的重载:

SetPassword([string] $Password){
    $UserPassword = ConvertTo-SecureString $Password -AsPlainText -Force
    $UserCredential = New-Object System.Management.Automation.PSCredential (
            $this.name, $UserPassword)
    $this.Credential = $UserCredential
}

SetPassword(){
    $Password = Read-Host "Please Enter Password"
    $this.SetPassword($Password)
}

我可能默认使用SecureString

SetPassword([securestring] $Password){
    $UserCredential = New-Object System.Management.Automation.PSCredential (
            $this.name, $Password)
    $this.Credential = $UserCredential
}

SetPassword([string] $Password){
    $UserPassword = ConvertTo-SecureString $Password -AsPlainText -Force
    $this.SetPassword($UserPassword)
}

SetPassword(){
    $Password = Read-Host "Please Enter Password" -AsSecureString
    $this.SetPassword($Password)
}