Playing with a new class feature in PowerShell v5, and I'm trying to get around my head if we can put methods in classes.
I tried below and played a little with it, but had no luck.
class Server {
[string]$computerName = "192.168.0.200"
[bool]$ping = (Test-Connection -ComputerName $computerName).count
}
$1 = [server]::new()
$1.computerName = "blah"
I tried to manually enter the computer name by setting the property, but then suggested that you would need it when creating the object
$1 = [server]::new($computerName = "192.168.0.200")
Exceptions I get
[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
The full $ error exception link is at http://pastebin.com/WtxfYzb5
Got some more use of $ this.prop, but you cannot initiate a constructor with your own parameters.
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
source
share