Santosh Benjamin's Weblog

Adventures with AppFabric, BizTalk & Clouds

Creating Hosts with Powershell

with 9 comments


[UPDATE]: The issue I had has now been solved. Please refer to the text below for the original issues as well as the solution

Context: Basically I was trying to write the powershell equivalent of the MSDN Article : Creating a Host using WMI

For the C# version of the sample here is the powershell equivalent
$putOptions = new-Object System.Management.PutOptions
$putOptions.Type = [System.Management.PutType]::CreateOnly;

[System.Management.ManagementClass]$objHostSettingClass = New-Object
System.Management.ManagementClass(“root\MicrosoftBizTalkServer”,”MSBTS_HostSetting”,$null)
[System.Management.ManagementObject]$objHostSetting = New-Object
System.Management.ManagementObject
$objHostSetting = $objHostSettingClass.CreateInstance()
$objHostSetting[“Name”] = $hostName
$objHostSetting[“HostType”] = $hostType
$objHostSetting[“NTGroupName”] = $NTGroupName
$objHostSetting[“AuthTrusted”] =$authTrusted
[System.Management.ManagementObject]($objHostSetting).Put(([System.Management.PutOptions]$putOptions));

This gives me the error
Exception calling “Put” with “1” argument(s): “You cannot call a method on a
null-valued expression.”

If i try the VBscript version (PS equivalent) as shown below
 $objLocator = New-Object -ComObject “WbemScripting.SWbemLocator”
$objService = $objLocator.ConnectServer(“.”,”root/MicrosoftBizTalkServer”)
$objHostSetting = $objService.Get(“MSBTS_HostSetting”)
$objHS = $objHostSetting.SpawnInstance_
$objHS.HostName = $hostName
$objHS.HostType = $hostType
$objHS.NTGroupName = $NTGroupName
$objHS.AuthTrusted = $authTrusted
$objHS.Put(2)

Then i get an error saying : the property is read only (name, hosttype etc)

changing the assignment to the following

$objHS.Properties_.Item(“Name”).value = $hostName

does not work  either, saying

You cannot call a method on a null-valued expression.

SOLUTION

In the original post, I had said that I was going to try to solve the problem through Reflection and indeed that was the only way i could get it to work.

 

In the code (for the C#/PS equivalent) shown above , it appears that the line [$objHostSetting.Put($options)] is the offender. Although $objHostSetting gets initialised correctly and all properties get set, the Put method cannot be called on it. At the time of invocation it seems that PS thinks its null.

 

It was a very painful process (for a PS newbie) and the reflection equivalent isn’t an exact translation of the C# either. The Invoke() method requires an object[] in C# but in PS you just pass the actual object and it will work

 

PS Script 

function bts-host-create([string]$hostName, [int]$hostType, [string]$NTGroupName, [bool]$authTrusted)

{

       $putOptions = new-Object System.Management.PutOptions

       $putOptions.Type = [System.Management.PutType]::CreateOnly;

      

       [System.Management.ManagementClass]$objHostSettingClass = New-Object System.Management.ManagementClass(“root\MicrosoftBizTalkServer”,”MSBTS_HostSetting”,$null)

       [System.Management.ManagementObject]$objHostSetting = New-Object System.Management.ManagementObject

       $objHostSetting = $objHostSettingClass.CreateInstance()

      

      

       $objHostSetting[“Name”] = $hostName

       $objHostSetting[“HostType”] = $hostType

       $objHostSetting[“NTGroupName”] = $NTGroupName

       $objHostSetting[“AuthTrusted”] =$authTrusted

      

       [Type[]] $targetTypes = New-Object System.Type[] 1

       $targetTypes[0] = $putOptions.GetType()

 

       $sysMgmtAssemblyName = “System.Management”

       $sysMgmtAssembly = [System.Reflection.Assembly]::LoadWithPartialName($sysMgmtAssemblyName)

       $objHostSettingType = $sysMgmtAssembly.GetType(“System.Management.ManagementObject”)

      

       [Reflection.MethodInfo] $methodInfo = $objHostSettingType.GetMethod(“Put”,$targetTypes)

       $methodInfo.Invoke($objHostSetting,$putOptions)

      

       Write-Host “Successfully created host named:  $hostName”

      

 

}

Here’s the C# code

public static void CreateHostThroughReflection(string HostName, int HostType, string NTGroupName, bool AuthTrusted)

        {

            try

            {

                PutOptions options = new PutOptions();

                options.Type = PutType.CreateOnly;

 

                //create a ManagementClass object and spawn a ManagementObject instance

                ManagementClass objHostSettingClass = new ManagementClass(“root\\MicrosoftBizTalkServer”, “MSBTS_HostSetting”, null);

                ManagementObject objHostSetting = objHostSettingClass.CreateInstance();

 

                //set the properties for the Managementobject

                objHostSetting[“Name”] = HostName;

                objHostSetting[“HostType”] = HostType;

                objHostSetting[“NTGroupName”] = NTGroupName;

                objHostSetting[“AuthTrusted”] = AuthTrusted;

 

                Type[] targetTypes = new Type[1];

                targetTypes[0]= typeof(PutOptions);

 

                object[] parameters = new object[1];

                parameters[0] = options;

               

                Type objType = objHostSetting.GetType();

                MethodInfo mi = objType.GetMethod(“Put”,targetTypes);

                mi.Invoke(objHostSetting, parameters);

 

                //create the Managementobject

                //objHostSetting.Put(options);

                System.Console.WriteLine(“Host – ” + HostName + ” – has been created successfully”);

            }

            catch (ManagementException mex)

            {

                Console.WriteLine(“Management Exception ” + mex.Message);

            }

            catch (Exception excep)

            {

                System.Console.WriteLine(“CreateHost – ” + HostName + ” – failed: ” + excep.Message);

            }

        }

Notice that the “Invoke” is different in the PS and the C#. Also notice how convoluted the PS is when trying to do a simple object.GetType() , but i guess PS wasnt meant for this sort of thing anyway, so we cant complain.

Hope this helps someone. Do let me know if it does. Use the code for whatever you want but i dont provide support  🙂

Advertisements

Written by santoshbenjamin

October 8, 2008 at 6:14 PM

9 Responses

Subscribe to comments with RSS.

  1. I am really enjoying the theme/design of your blog. Do you ever run into any
    web browser compatibility issues? A handful of my blog visitors have complained about my site not working correctly in
    Explorer but looks great in Chrome. Do you have any recommendations to help fix this issue?
    .

  2. I create a leave a response when I appreciate a article on a site or
    if I have something to contribute to the discussion. Usually it is triggered by the sincerness displayed in the article I
    read. And on this article Creating Hosts with Powershell | Santosh Benjamin’s Weblog.
    I was moved enough to leave a thought 😉 I do
    have 2 questions for you if it’s okay. Is it simply me or does
    it appear like a few of the comments appear like coming
    from brain dead visitors? 😛 And, if you are writing
    at additional social sites, I’d like to keep up with you.
    Could you list all of your community pages like your linkedin profile, Facebook page or
    twitter feed?. If you need to twitter you should definitely
    maintain your facebook consideration updated.

    If you would like twitter be sure to keep
    the facebook profile updated.
    twitter help in raising customer base, search engine rank, and so on

    twitter

    May 23, 2014 at 2:20 AM

  3. It’s hard to come by experienced people on this topic, but you
    seem like you know what you’re talking about! Thanks. facebook
    facebook
    facebook

    facebook

    September 1, 2014 at 6:15 AM

  4. Hi there, simply became aware of your blog through Google, and located that it is really informative.
    I’m gonna watch out for brussels. I will appreciate in the event
    you proceed this in future. Lots of folks will be benefited out of your writing.
    Cheers! twitter
    twitter
    twitter

    twitter

    September 9, 2014 at 6:55 AM

  5. Wow that was strange. I just wrote an really long comment
    but after I clicked submit my comment didn’t show up.
    Grrrr.. well I’m not writing all that over again. Anyways, just wanted to say fantastic blog!
    instagram
    instagram

    instagram

    September 20, 2014 at 3:23 AM

  6. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new
    initiative in a community in the same niche. Your blog provided us
    valuable information to work on. You have done a wonderful job!
    youtube
    youtube
    youtube

    youtube

    September 23, 2014 at 12:56 PM

  7. I am truly thankful to the owner of this web page who has shared this great paragraph at at this place.
    twitter
    twitter

    twitter

    September 23, 2014 at 8:52 PM

  8. When someone writes an post he/she keeps the idea of a user in his/her brain that how a user can understand it.
    Therefore that’s why this article is great. Thanks!

    instagram
    instagram
    instagram

    instagram

    September 23, 2014 at 9:45 PM

  9. VMware Certified Advanced Professional 6 (Desktop and Mobility Deployment) – The industry-recognized VCAP6-DTM Deploy certification validates that you know how to deploy and optimize VMware Horizon 6 (with View) environments. It demonstrates that you have the knowledge and abilities necessary to leverage best practices to provide a scalable and dependable Business Mobility platform for your company. Some of the subjects include: Configuring and managing Horizon View components, configuring cloud pod archituecture, configuring Group Policy settings related to Horizon View, Configuring and optimizing desktop images for Horizon View & Mirage, Configuring and managing App Volumes AppStacks, Configuring desktop pools, Configuring and deploying ThinApp packaged applications, Configuring VMWare Identity Manager, etc.Sebastian’s take on the VCAP6 exam: “In my own point of view VCAP6 exam is way better experience compared to VCAP5, the new exam appears just like VMware HOL. The user interface is straightforward, questions are arranged on the right area of the screen, and can be hidden aside or restored when desired. My advise on the questions windowpane: if you opt to make it floating, you should know how to restore it back. I ended up moving it all around because I fail to remember how to restore it back. The 2 arrows that seemed like control buttons on top were meant to dock the window to right or left. Fonts could be resized, which i believe was much better than scrolling down and up the question. The response speed of the entire user interface was considerably quicker as compared to VCAP5.5, and there was no lagging period experienced when changing from window to window. Something to remember: BACKSPACE key is not working! I think this is good since you don’t reload your examination window in error, however, it can be irritating occasionally when you type something incorrectly and you need to select and press Del to remove. The Desktop and shortcuts were organized very well, and needed programs like browser or Mirage console can be launched. You will find there’s decent interface for Remote Desktop Manager where you’ll discover all essential RDP connection to servers or desktops without the need to type username and password. The web browser had all the links in the Favorite Bar. Right at that moment I am writing this, there is no extra Thirty minute extension for Non-Native English speaker at No-Native English country, which is a bummer. You will find 39 question to respond within the 3 hours time, which can be actually really hard for non-native English speakers like me. Some questions take time to finish, therefore it is better to skip the questions that you cannot answer, and complete those you can. At the end of the thirty-nine questions, you’ll be able to revisit the uncompleted questions when you have time. Don’t waste a long time on one single question! The examination blue print can be obtained on my website at Szumigalski.com. It is well-organized and following it for the examination preparation can help a great deal. Needless to say, the most suitable is if you’ll have lots of practical experience! I’m truly very pleased with the examination experience, though I passed this time by tiny margin, but I really know what I missed for the examination, study from the mistakes and practice harder to get familiar myself with the environment. This qualification will unquestionably open up your job prospects!”

    szumigalski

    February 16, 2017 at 12:11 AM


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: