如何在PowerShell类中创建可直接调用实例属性的Ping方法
实现方案
完全可以实现你要的调用效果,只需要调整类中Ping方法的参数定义和内部取值逻辑即可,不需要额外传入参数。
方案1:纯无参Ping方法
直接删除方法的入参,内部直接读取当前实例的ComputerName属性:
Class Device { [string]$ComputerName [string]$Status [string]$Manufacturer [string]$Model [string]$SerialNumber [Void]Ping() { # 直接读取当前实例已赋值的ComputerName属性 $Echo_Reply = Test-Connection -ComputerName $this.ComputerName -Count 1 -Quiet $this.Status = $Echo_Reply } }
调整后你就可以直接按预期方式调用:
$Device = [device]::new() $Device.ComputerName = 'ComputerOne' # 无需传参直接调用 $Device.Ping() # 查看Ping结果 $Device.Status
方案2:兼容两种调用场景(更灵活)
如果你想要保留「临时指定Ping目标」的能力,同时支持无参调用,可以给参数加默认值指向实例本身的ComputerName属性:
Class Device { [string]$ComputerName [string]$Status [string]$Manufacturer [string]$Model [string]$SerialNumber [Void]Ping([string]$ComputerName = $this.ComputerName) { $Echo_Reply = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet $this.Status = $Echo_Reply } }
这种写法下两种调用方式都可以生效:
- 无参调用
$Device.Ping():自动使用实例已赋值的ComputerName属性 - 传参调用
$Device.Ping('ComputerTwo'):临时Ping指定目标,状态同步更新到实例的Status字段
优化建议
可以在Ping方法开头加非空判断,避免ComputerName未赋值时执行报错:
[Void]Ping() { if ([string]::IsNullOrWhiteSpace($this.ComputerName)) { throw "当前实例未赋值ComputerName属性,请先赋值后再调用Ping方法" } $Echo_Reply = Test-Connection -ComputerName $this.ComputerName -Count 1 -Quiet $this.Status = $Echo_Reply }
内容的提问来源于stack exchange,提问作者Abraham Zinala
相关产品推荐
相关产品推荐

