Unable to create a final object using classes

Tagged: ,

This topic contains 1 reply, has 1 voice, and was last updated by Profile photo of Wei-Yen Tan Wei-Yen Tan 6 months, 3 weeks ago.

  • Author
    Posts
  • #61035
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

    I decided to have a deep dive into learning classes and started looking at the Powershell Unplugged 2016 with Don Jones and Jeffrey Snover.

    I decided to start by doing something simple. Use a restful api to grab info about the WAN ip. In this case i am using http://ip-api.com to get the details. I have created my class just like what its in the demo but it comes up with an error to say that

    
    value of type 
    "System.Management.Automation.PSCustomObject" to type 
    "Get-WhoisInformation.WhoisInformation"."
    At line:58 char:3
    +         Write-Output ([WhoisInformation]$object)
    
    

    Any help appreciated. I am pretty sure it is something small I am missing. I am even happy if it is just guidance.

    function Get-WhoisInformation
    {
    
        
    	[CmdletBinding()]
        [OutputType("WhoisInformation")]
    	param
    	(
    		[Parameter(Mandatory = $false,
    				   Position = 1)]
    		[Alias('ipaddress')]
    		[string]$domain
    	)
    	
    	class WhoisInformation
    	{
    		[string]$city;
    		[string]$country;
    		[string]$countryCode;
    		[string]$company;
            [string]$query;
    		[string]$lat;
    		[string]$lon;
    		[string]$region;
    		[string]$timezone;
    		[string]$zip;
    	}
    	
    	Update-TypeData -TypeName WhoisInformation -MemberType ScriptProperty -MemberName Company -Value { $this.org } -Force
    	Update-TypeData -TypeName WhoisInformation -MemberType ScriptProperty -MemberName domain -Value { $this.query } -Force
    	Update-TypeData -TypeName WhoisInformation -DefaultDisplayPropertySet domain, Company, Timezone, City -DefaultDisplayProperty domain -DefaultKeyPropertySet domain -Force
    	
    
    	if ($domain)
    	
    	{
    		$object = Invoke-RestMethod -Uri http://ip-api.com/json/$domain
    	}
    	else
    	{
    		$object = Invoke-RestMethod -uri http://ip-api.com/json/
    	}
    	
    	
    		
    		Write-Output ([WhoisInformation]$object)
    
    	
    	
    
    }
    
    
  • #61045
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

    Hi guys,

    I reviewed it again. Went through the webinar and the demo.

    With a little bit of experimentation found out the reason why.

    Reason why it failed is because in my classes, I did not include all the properties found in Invoke-Restmethod.

    I used the tool Convert-ObjecttoClass and copied that. Applied it the same way that Jeffrey did and what do you know...it worked.
    So lesson to take away is that all properties need to be added to the class. Hope that helps.

You must be logged in to reply to this topic.