Good day. I am working on an AD computer object creation script that has evolved. I have looked for some ways to dynamically pull data out of a storage object; this started with a hashtable, but then I realized I need multiple "columns" of values so that I could request a 2nd or 3rd value that is stored.
This led me to the creation of some PSObjects. I have a simple array as well.
$SiteCode_SHA = [PSCustomObject]@{
CountryCode = "CH"
SiteCode = "SHA"
ContainerCode = "CHA"
}
$SiteCode_IND = [PSCustomObject]@{
CountryCode = "IN"
SiteCode = "MOB"
ContainerCode = "IND"
}
[array]$ComputerTypeArray = "LT", "PC", "PR"
[string]$SiteCodeInput = (Read-Host -Prompt "Prompt #1 Input Options: SHA, IND")
$ProposedComputerName = '$SiteCode_' $SiteCodeInput '.CountryCode'
I am attempting to build a variable that contains the CountryCode from one of the $SideCode_XXX objects, plus the SiteCode from the same object, plus a value from the $ComputerTypeArray
(which I am successfully retrieving through Read-Host.)
I have a three character variable that is being input through Read-Host that matches the suffix of the $SiteCode_XXX object. I cannot figure out how to dynamically use the object and its contained values after obtaining input from the user.
Concatenation of texts does not allow me to utilize the PSObject or its contained values, which I expected to be the failure point, but I cannot figure out the standard for getting around this. The goal is to set the variable $ProposedComputerName
to "IN" if the $SiteCodeInput is "IND", or "CH" if the $SiteCodeInput
is "SHA". (There are other components to the computer name that I am dealing with once this single problem is resolved.)
Thank you for your time.
CodePudding user response:
Instead of using multiple variables, organize your data into a hashtable that use the site code as its key for each entry:
# define the data objects, store them in a simple array
$Sites = @(
[PSCustomObject]@{
CountryCode = "CH"
SiteCode = "SHA"
ContainerCode = "CHA"
}
[PSCustomObject]@{
CountryCode = "IN"
SiteCode = "MOB"
ContainerCode = "IND"
}
)
# now create a hashtable that maps each site code to the corresponding object
$SiteCodeMap = @{}
$Sites |ForEach-Object {
$SiteCodeMap[$_.SiteCode] = $_
}
# ... and now we're ready to take user input
$SiteCodeInput = (Read-Host -Prompt "Prompt #1 Input Options: SHA, IND")
# remember to test whether the input is valid
if($SiteCodeMap.ContainsKey($SiteCodeInput)){
# use valid site code to resolve the corresponding data object and grab the CountryCode value
$ProposedComputerName = $SiteCodeMap[$SiteCodeInput].CountryCode
} else {
Write-Warning "No site with site code '$SideCodeInput' exists!"
}