none
Dynamic Variable Names RRS feed

  • Question

  • Looking to create a script intended to run for extended period of time and track data for individual users.

    $WatchList contains an array of SamAccountNames

    ForEach($Person in $WatchList)
    {
    $A = Get-ADUser $Person -Properties * | Select DisplayName,etc......
    $Date = (Get-Date).ToString("MMM-dd-yyyy")
    $Time = (Get-Date).ToString("HH:mm:ss")
    $UserInfoVariable = $Person + "Info"
    New-Variable -Name $UserInfoVariable -Value @{}

    #Get some stats for user
    #Store stats in a PSObject
    $Obj = New-Object PSObject
    $Obj | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $A.DisplayName
    $Obj | Add-Member -MemberType NoteProperty -Name "Stat1" -Value ""
    $Obj | Add-Member -MemberType NoteProperty -Name "Stat2" -Value ""
    $Obj | Add-Member -MemberType NoteProperty -Name "Stat3" -Value ""

    #All good to this point

    >> $UserInfoVariable.Add($Person,$Obj)
    #The above line fails with the following error:
    # Method invocation failed because [System.String] does not contain a method named 'Add'.
    # At Script.ps1:xx char:x
    # +             "$UserInfoVariable".Add($Person,$Obj)
    # +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    # + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    # + FullyQualifiedErrorId : MethodNotFound

    }

    Is there any way to have the $UserInfoVariable.Add command see as the created variable as the actual value "$SamAccountNameInfo" which was properly created in the New-Variable command earlier?

    I could hard code the variable names but I think I would need duplicate the info gathering loop for each user. Plus if I change any of the names in the $WatchList I would then have to change the associated variables throughout the entire script.

    Thank you,

    Steve

    • Moved by Bill_Stewart Monday, December 17, 2018 6:38 PM User answered own question
    Thursday, September 27, 2018 8:45 PM

All replies

  • Just carefully read the error:

    Method invocation failed because [System.String] does not contain a method named 'Add'

    You are trying to access a variable by its name.  Can't be done directly.

    $var = Get-Variable  $UserInfoVariable
    $var.Add($Person,$Obj)


    \_(ツ)_/


    • Edited by jrv Thursday, September 27, 2018 9:34 PM
    Thursday, September 27, 2018 9:31 PM
  • Thank you. Failed to see the forest through the trees.

    Your message and taking a step back got me back on track with this. Realized I was approaching this incorrectly anyway. I did not actually need to name the variable itself since I was identifying the individuals as the hash key.

    Thanks again.

    Cheers!

    Thursday, October 4, 2018 12:09 PM