Forum Discussion

charlie4872's avatar
charlie4872
Brass Contributor
Mar 06, 2020
Solved

Inserting variable in command string

I am trying to make a small script to get user, computer and SID info for changing a registry value. Below is my script...   $computer = read-host -prompt 'Enter Computername' $user = read-host -p...
  • Joshua King's avatar
    Joshua King
    Mar 09, 2020

    Ahh, what you'll find is that your $sid variable doesn't actually contain what you're expecting it to contain.

     

    The way it's being used you're wanting it to be a string of just the SID, but it's currently an object with one property. (Seems like a nitpicky distinction but id does have implications in situations like this.)

     

    If you call $sid, what you'll see output atm is:

     

    SID
    ---
    S-1-5-21-7375663-6890924511-1272660413-2944159

    but what you actually want is just

    S-1-5-21-7375663-6890924511-1272660413-2944159

     

    All of that is to say, either change this line:

    $sid = Get-Aduser -identity $user | select-object SID

     

    To

    $sid = Get-Aduser -identity $user | select-object -ExpandProperty SID

    The -ExpandProperty option "expands" the select property such that it's the new "Object" being returned, rather than selecting child properties of the parent object. Basically it means you just get back a string...

     

    And alternative to that approach is:

    $sid = (Get-Aduser -identity $user).SID

    Which pulls that property out and has much the same effect as the expandproperty.

     

    One final option is to reference that property directly inside the Invoke-Command scriptblock:

    $($Using:sid.SID)

     

    This method actually opens up a few posibilities. For example, if you got rid of the select-object and did something like

    $UserObject = Get-Aduser -identity $user

     

    Then you could reference the sid when needed:

    $($Using:UserObject.SID)

     

    But elsewhere you could also use the other properties:

    $($Using:UserObject.SamAccountName)

     

    -----

     

    Sorry that was a touch long winded, just wanted to fully playout the problem and potential solutions :smile:

Resources