如何在PowerShell中正确重载方法
我有一个用户类,它有一个重载方法“SetPassword”,用于填充用户凭据:如何在PowerShell中正确重载方法,powershell,methods,overloading,Powershell,Methods,Overloading,我有一个用户类,它有一个重载方法“SetPassword”,用于填充用户凭据: class User { ... [PSCredential] $Credential ... SetPassword([string] $Password){ $UserPassword = ConvertTo-SecureString $Password -AsPlainText -Force $UserCredential = New-Object
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()
有没有一种更好的方法可以做到这一点,它不会像我在这里看到的那样有重复的代码?调用前面的重载中最具体的重载:
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)
}
调用上一个重载中最具体的重载:
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)
}
建议:如果您使用的是类,请使用类型构造函数,而不是
newobject
。。如果您打算使用v5
功能,那么为了保持一致性和可读性,不妨利用所有这些功能[PSCredential]::new($this.Name,$UserPassword)
建议:如果使用类,请使用类型构造函数而不是新对象。。如果您打算使用v5
功能,那么为了保持一致性和可读性,不妨利用所有这些功能<代码>[PSCredential]::新建($this.Name,$UserPassword)