Questions about using variables with params

This topic contains 5 replies, has 2 voices, and was last updated by Profile photo of Travis Hubbard Travis Hubbard 2 years, 1 month ago.

  • Author
    Posts
  • #19919
    Profile photo of Travis Hubbard
    Travis Hubbard
    Participant

    Hey guys I think I have a simple problem.

    I am trying to write a cmdlet that does some extra work related to VM creation. The problem I am encountering is when trying to pass a variable I created into the -MemoryStartupBytes param of the New-VM cmdlet.

    My cmdlet prompts the user for the value of RAM to assign the VM. I have $RAM defined as an INT. However when I try to pass the $RAM variable to the New-VM -MemoryStartupBytes parameter it fails with the attached error.

    I've tried assigning the $RAM variable the contents of 3gb and 3000. What am I missing here?

  • #19921
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    The -RAM parameter wants and integer, so it should be 3. Despite 3000 being a valid integer...

    PS C:\Users\rsimmers> 3000 -is [int]
    True

    There is most likely a range specified (e.g. 1-16), so 3000 will not work. 3gb is a [string], which also would fail when it's passed indicating cannot convert a string to an int.

  • #19925
    Profile photo of Travis Hubbard
    Travis Hubbard
    Participant

    Thanks for your help Rob, however when I change the variable to 3 I get the attached result.

  • #19927
    Profile photo of Travis Hubbard
    Travis Hubbard
    Participant

    Also, for some clarification the reason I was trying "3gb" originally was because the New-VM cmdlet natively supports 3gb, 512mb et cetera as a valid amount for the -MemoryStartupBytes param.

  • #19932
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    As you are already seeing, -RAM is a bit ambiguous. I would highly recommend change the variable to RAMinGB so that you tell other users exactly what is expected with appropriate help messages. Something like so should work:

    function New-2012r2VM {
        param(
            [int]$RAMinGB
        )
    
        begin{}
        process{New-VM -MemoryStartupBytes ($RAMinGB * 1gb)}
        end{}
    }
    
    function New-VM {
    param (
        [long]$MemoryStartupBytes
    )
    
        "Setting start bytes to {0}" -f $MemoryStartupBytes
    }
    
    New-2012r2VM -RAMinGB 3
    
    Setting start bytes to 3221225472
    
    
  • #19933
    Profile photo of Travis Hubbard
    Travis Hubbard
    Participant

    It was the ($RAMinGB * 1gb) that was key to resolving my issue. I've also changed the name of the variable like you recommended. That worked like a charm. Thank you very much for your help.

You must be logged in to reply to this topic.