使用 PowerShell v5 中的新类函数,如果我们可以将方法放入类中,我正在努力解决问题。
我已经尝试了以下方法并玩了一段时间,但没有运气。
class Server {
[string]$computerName = "192.168.0.200"
[bool]$ping = (Test-Connection -ComputerName $computerName).count
}
$1 = [server]::new()
$1.computerName = "blah"
我尝试通过设置属性手动输入计算机名称,但后来我假设您在创建对象时需要它
$1 = [server]::new($computerName = "192.168.0.200")
我得到的例外是
[ERROR] Exception calling ".ctor" with "0" argument(s): "Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the
[ERROR] command again."
[ERROR] At D:\Google Drive\Projects\VSPowerShell\DiscoveryFramework\DiscoveryFramework\DiscoveryFramework\class.ps1:12 char:1
[ERROR] + $1 = [server]::new()
[ERROR] + ~~~~~~~~~~~~~~~~~~~~
[ERROR] + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
[ERROR] + FullyQualifiedErrorId : ParameterBindingValidationException
[ERROR]
[DBG]: PS C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE>
[DBG]: PS C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE> $1
Server
[DBG]: PS C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE> $1.gettype()
Server
来自 $error 的完整异常链接位于http://pastebin.com/WtxfYzb5
进一步使用了 $this.prop,但您不能使用自己的参数启动构造函数。
PS path:\> class Server {
[string]$computerName = "192.168.0.200"
[bool]$ping = (Test-Connection -ComputerName $this.computerName).count
}
PS path:\>
PS path:\> $var = [server]::new()
PS path:\> $var
computerName ping
------------ ----
192.168.0.200 True