Global Variables with dynamic names

I’m creating dynamic variable names from input values.

I’m able to create a global variable using:

$global:MyVar = “Do Something”

$MyVar results in
Do Something

But when I build the ‘MyVar’ name
$var01 = ‘My’
$var02 = ‘Var’
$DynamicMyVar = “{0}Custom{1}” -f $var01,$var02

$global:$DynmaicMyVar = “Do something Else” fails

Is it possible to create global variables using this approach?

I’ve tried
${global:$DynmaicMyVar} = “Do something Else”
$global:$DynmaicMyVar.toString() = “Do something Else”
$global:$($DynmaicMyVar) = “Do something Else”

I’d like $MyCustomVar now to be global and be
Do Something Else

Use the New-Variable cmdlet

$var01 = 'My'
$var02 = 'Var'
$DynamicMyVar = "{0}Custom{1}" -f $var01,$var02

New-Variable -Name $DynamicMyVar -Scope "Global" -Value "Do something Else"

$MyCustomVar

Results:

Do something Else

As a suggestion, having dynamic variables can be a little hard to keep track of sometimes. I typically will use a hash table for this purpose.

For Example:

$var01 = 'My'
$var02 = 'Var'
$DynamicMyVar = "{0}Custom{1}" -f $var01,$var02
$DynamicMyVar2 = "{0}Custom2{1}" -f $var01,$var02

$global:dynamicContent = @{}
$dynamicContent += @{$DynamicMyVar = "Do somthing Else"}
$dynamicContent += @{$DynamicMyVar2 = "Do somthing Else again"}

# Output entire hash table
$dynamicContent

# Output just the MyCustomVar value
$dynamicContent.MyCustomVar

# Output just the MyCustom2Var value
$dynamicContent.MyCustom2Var

Results:

Name                           Value                                                                                                                                     
----                           -----                                                                                                                                     
MyCustomVar                    Do somthing Else                                                                                                                          
MyCustom2Var                   Do somthing Else again                                                                                                                    
Do somthing Else
Do somthing Else again

That’s getting me closer.

Everything runs fine, but the Dynamic Global variable doesn’t “load” data from the ADUC query.

$Code = '1234'
$Area = 'West'

$SearchBaseVariableName = "{0}{1}" -f $Area,$Code
$SearchBaseVariable = New-Variable -Name $VariableName

if ($Code -and $Area) 
    {$SearchBaseVariable = "OU={0},OU={1},OU=REGION,DC=domain,DC=local" -f $ModeCode,$Area}
    elseif ($Area)
    {$SearchBaseVariable = "OU={0},OU=REGION,DC=domain,DC=local" -f $Area}	
    else
	{$SearchBaseVariable = "OU=REGION,DC=domain,DC=local"}

# Manually entering a Variable Name and running line works (adds ADUC data to variable West1234 for further processing)
# Ie. $West1234.sAMAccountName | sort sAMAccountName
$global:West1234 = Get-ADComputer -SearchBase $SearchBaseVariable -Filter * -Properties *

$GlobalVariableName = "{0}{1}" -f $Area,$Code

New-Variable -Name $GlobalVariableName -Scope "Global" -Value "Get-ADComputer -SearchBase $SearchBaseVariable -Filter * -Properties *"

Hi Grant,
That’s because you are not actually executing any code when you set your value in this line, rather you are just passing in a string of text.

New-Variable -Name $GlobalVariableName -Scope "Global" -Value "Get-ADComputer -SearchBase $SearchBaseVariable -Filter * -Properties *"

To have it execute that code, rather than just pass that as a string of text, take away the double quotes surrounding it. These indicate to PowerShell that it is a text string. Instead use Parenthesis. These indicate to PowerShell that the code inside the parenthesis needs to be executed and provide the resulting output to the -Value Parameter.

IE.
Using Double-quotes:

$Code = '1234'
$Area = 'West'

$GlobalVariableName = "{0}{1}" -f $Area,$Code
$SearchBaseVariable = "dc=domain,dc=local"

New-Variable -Name $GlobalVariableName -Scope "Global" -Value "Get-ADComputer -SearchBase $SearchBaseVariable -Filter * -Properties *"

$West1234

Results in the string value provided with the $SearchBaseVariable resolved being stored in the variable:

Get-ADComputer -SearchBase dc=ca,dc=lab -Filter * -Properties *

Using Parenthesis:

$Code = '1234'
$Area = 'West'

$GlobalVariableName = "{0}{1}" -f $Area,$Code
$SearchBaseVariable = "dc=domain,dc=local"

New-Variable -Name $GlobalVariableName -Scope "Global" -Value (Get-ADComputer -SearchBase $SearchBaseVariable -Filter * -Properties *)

$West1234

Results in the code being executed and the results stored in the variable:

AccountExpirationDate                : 
accountExpires                       : 9223372036854775807
AccountLockoutTime                   : 
AccountNotDelegated                  : False
AllowReversiblePasswordEncryption    : False
AuthenticationPolicy                 : {}
AuthenticationPolicySilo             : {}
BadLogonCount                        : 0
badPasswordTime                      : 0
badPwdCount                          : 0
CannotChangePassword                 : False
CanonicalName                        : 
Certificates                         : {}
CN                                   : linux
codePage                             : 0
CompoundIdentitySupported            : {False}
countryCode                          : 0
Created                              : 2/20/2016 2:08:39 AM
createTimeStamp                      : 2/20/2016 2:08:39 AM
Deleted                              : 
Description                          : 
DisplayName                          : 
DistinguishedName                    : 
DNSHostName                          : linux.domain.local
DoesNotRequirePreAuth                : False
dSCorePropagationData                : {6/23/2016 5:25:46 PM, 6/23/2016 4:12:09 PM, 6/23/2016 4:06:18 PM, 6/23/2016 4:02:40 PM...}
Enabled                              : True
HomedirRequired                      : False
HomePage                             : 
instanceType                         : 4
IPv4Address                          : 
IPv6Address                          : 
isCriticalSystemObject               : False
isDeleted                            : 
KerberosEncryptionType               : {DES, RC4, AES128, AES256}
LastBadPasswordAttempt               : 
LastKnownParent                      : 
lastLogoff                           : 0
lastLogon                            : 131154305112537821
LastLogonDate                        : 8/11/2016 11:29:33 AM
lastLogonTimestamp                   : 131154065738370991
localPolicyFlags                     : 0
Location                             : 
LockedOut                            : False
logonCount                           : 235
ManagedBy                            : 
MemberOf                             : {}
MNSLogonAccount                      : False
Modified                             : 8/11/2016 11:29:33 AM
modifyTimeStamp                      : 8/11/2016 11:29:33 AM
msDS-SupportedEncryptionTypes        : 31
msDS-User-Account-Control-Computed   : 0
Name                                 : linux
nTSecurityDescriptor                 : System.DirectoryServices.ActiveDirectorySecurity
ObjectCategory                       : CN=Computer,CN=Schema,CN=Configuration,DC=domain,DC=local
ObjectClass                          : computer
ObjectGUID                           : 
objectSid                            : 
OperatingSystem                      : 
OperatingSystemHotfix                : 
OperatingSystemServicePack           : 
OperatingSystemVersion               : 
PasswordExpired                      : False
PasswordLastSet                      : 2/20/2016 2:08:39 AM
PasswordNeverExpires                 : True
PasswordNotRequired                  : False
PrimaryGroup                         : CN=Domain Computers,CN=Users,DC=domain,DC=local
primaryGroupID                       : 515
PrincipalsAllowedToDelegateToAccount : {}
ProtectedFromAccidentalDeletion      : False
pwdLastSet                           : 131004293196070069
SamAccountName                       : linux$
sAMAccountType                       : 805306369
sDRightsEffective                    : 15
ServiceAccount                       : {}
servicePrincipalName                 : {HOST/linux.domain.local, HOST/LINUX}
ServicePrincipalNames                : {HOST/linux.domain.llocal, HOST/LINUX}
SID                                  : 
SIDHistory                           : {}
TrustedForDelegation                 : False
TrustedToAuthForDelegation           : False
UseDESKeyOnly                        : False
userAccountControl                   : 69632
userCertificate                      : {}
UserPrincipalName                    : 
uSNChanged                           : 2450065
uSNCreated                           : 332255
whenChanged                          : 8/11/2016 11:29:33 AM
whenCreated                          : 2/20/2016 2:08:39 AM

AccountExpirationDate                : 
accountExpires                       : 9223372036854775807
AccountLockoutTime                   : 
AccountNotDelegated                  : False
AllowReversiblePasswordEncryption    : False
AuthenticationPolicy                 : {}
AuthenticationPolicySilo             : {}
BadLogonCount                        : 0
badPasswordTime                      : 0
badPwdCount                          : 0
CannotChangePassword                 : False
CanonicalName                        : domain.local/Computers/MEMBERSERVER
Certificates                         : {}
CN                                   : MEMBERSERVER
codePage                             : 0
CompoundIdentitySupported            : {False}
countryCode                          : 0
Created                              : 2/23/2016 11:32:32 AM
createTimeStamp                      : 2/23/2016 11:32:32 AM
Deleted                              : 
Description                          : 
DisplayName                          : 
DistinguishedName                    : CN=MEMBERSERVER,CN=Computers,DC=domain,DC=local
DNSHostName                          : MemberServer.domain.local
DoesNotRequirePreAuth                : False
dSCorePropagationData                : {6/23/2016 5:25:46 PM, 6/23/2016 4:12:09 PM, 6/23/2016 4:06:18 PM, 6/23/2016 4:02:40 PM...}
Enabled                              : True
HomedirRequired                      : False
HomePage                             : 
instanceType                         : 4
IPv4Address                          : 
IPv6Address                          : 
isCriticalSystemObject               : False
isDeleted                            : 
KerberosEncryptionType               : {RC4, AES128, AES256}
LastBadPasswordAttempt               : 
LastKnownParent                      : 
lastLogoff                           : 0
lastLogon                            : 131146318092427921
LastLogonDate                        : 8/2/2016 11:09:53 AM
lastLogonTimestamp                   : 131146277938824146
localPolicyFlags                     : 0
Location                             : 
LockedOut                            : False
logonCount                           : 159
ManagedBy                            : 
MemberOf                             : {}
MNSLogonAccount                      : False
Modified                             : 8/2/2016 11:09:53 AM
modifyTimeStamp                      : 8/2/2016 11:09:53 AM
msDS-SupportedEncryptionTypes        : 28
msDS-User-Account-Control-Computed   : 0
Name                                 : MEMBERSERVER
nTSecurityDescriptor                 : System.DirectoryServices.ActiveDirectorySecurity
ObjectCategory                       : CN=Computer,CN=Schema,CN=Configuration,DC=domain,DC=local
ObjectClass                          : computer
ObjectGUID                           : 
objectSid                            : 
OperatingSystem                      : Windows Server 2012 R2 Standard Evaluation
OperatingSystemHotfix                : 
OperatingSystemServicePack           : 
OperatingSystemVersion               : 6.3 (9600)
PasswordExpired                      : False
PasswordLastSet                      : 7/15/2016 9:08:55 AM
PasswordNeverExpires                 : False
PasswordNotRequired                  : False
PrimaryGroup                         : CN=Domain Computers,CN=Users,DC=domain,DC=local
primaryGroupID                       : 515
PrincipalsAllowedToDelegateToAccount : {}
ProtectedFromAccidentalDeletion      : False
pwdLastSet                           : 131130653358644547
SamAccountName                       : MEMBERSERVER$
sAMAccountType                       : 805306369
sDRightsEffective                    : 15
ServiceAccount                       : {}
servicePrincipalName                 : {TERMSRV/MEMBERSERVER, TERMSRV/MemberServer.domain.local, WSMAN/MemberServer, WSMAN/MemberServer.ca.lab...}
ServicePrincipalNames                : {TERMSRV/MEMBERSERVER, TERMSRV/MemberServer.domain.local, WSMAN/MemberServer, WSMAN/MemberServer.ca.lab...}
SID                                  : 
SIDHistory                           : {}
TrustedForDelegation                 : False
TrustedToAuthForDelegation           : False
UseDESKeyOnly                        : False
userAccountControl                   : 4096
userCertificate                      : {}
UserPrincipalName                    : 
uSNChanged                           : 2355836
uSNCreated                           : 364695
whenChanged                          : 8/2/2016 11:09:53 AM
whenCreated                          : 2/23/2016 11:32:32 AM