Using custom objects in Power Shell

<#
returns the client-object type string with the specified properties
#>
function ClientObject($clientID,$command, $dbServer,$dbUser,$dbPwd,$dataSource )
{
     $er = "" | Select ClientID,Command,DBServer,DBUser,DBPwd,DataSource,ConnectionString
     $er.ClientID = $clientID
     $er.Command = $command
     $er.DBServer = $dbServer
     $er.DBUser = $dbUser
     $er.DBPwd = $dbPwd
     $er.DataSource = $dataSource
     $er.ConnectionString = "Password="+$er.DBPwd+";User ID="+$er.DBUser+";Data Source="+$er.DataSource+";Persist Security Info=True";
    
     $er = $er | Add-Member ScriptMethod GetClientId {$this.ClientID} -PassThru
     $er = $er | Add-Member ScriptMethod GetCommand {$this.Command} -PassThru
     $er = $er | Add-Member ScriptMethod GetDBServer {$this.DBServer} -PassThru
     $er = $er | Add-Member ScriptMethod GetDBUser {$this.DBUser} -PassThru
     $er = $er | Add-Member ScriptMethod GetDBPwd {$this.DBPwd} -passThru
     $er = $er | Add-Member ScriptMethod GetDataSource {$this.DataSource} -PassThru
     $er = $er | Add-Member ScriptMethod GetConnectionString {$this.ConnectionString} -PassThru
    
    $er = $er | Add-Member ScriptMethod ToString {
                 Write-Host ("ClientID: " + $this.ClientID )
                 Write-Host ("Command: " + $this.Command )
                Write-Host ("DBServer: " + $this.DBServer )
                Write-Host ("DBUser: " + $this.DBUser )
                Write-Host ("DBPwd: " + $this.DBPwd )
                Write-Host ("DataSource: " + $this.DataSource )
                Write-Host ("ConnectionString: " + $this.ConnectionString )
               
            } -PassThru -Force
    $er
}

Now, we can create the custom object as required. This can be done using the following syntax:

$clientObj  = ClientObject $clientId $command $server $username $password $datasource;
This is simply like the one we use in  other Object Oriented programming language to call the constructor of a class.
Now, we can call the methods of the object as:
$clientObj.GetCommand();
and so on.



This will be handy when we need to have custom objects in Power Shell.

No comments:

Post a Comment