Changing a variable based on output

67 views Asked by At

Good Afternoon, Just want to start by saying I am totally new with PS, and am really sorry if my approach to this is long winded or inaccurate.

I have a list of computernames that declared as individual Variables that my colleagues have provided me :

$Jon = "Abc1234"
$Mike = "Abc6789"
  • another 10 hostnames

I then ask the user if they want to send the files to another PC :

$Targetuser = Read-Host 'Who would you like to send it to?'

What I would like is the output from the above to change to the hostname, but I am unsure of how to do this. Essentially, if the output was Mike, to change the $targetuser variable to $Abc6789

Thanks in advance

1

There are 1 answers

3
Mathias R. Jessen On BEST ANSWER

Dynamically named variables is almost always a bad idea. Instead, use a dictionary type, like a hashtable:

# Define user->host dictionary
$Hostnames = @{
  Jon  = "Abc1234"
  Mike = "Abc6789"
}

# Ask user for target user
$TargetUser = Read-Host 'Who would you like to send it to?'

# Keep asking until the enter an actual user name
while(-not $Hostnames.ContainsKey($TargetUser)){
  Write-Host "No hostname found for user '${targetUser}'!"
  Write-Host "Choose one of:"
  Write-Host ($Hostnames.Keys -join "`n")
  $TargetUser = Read-Host 'Who would you like to send it to?'
} 

# Get the associated hostname
$TargetHost = $Hostnames[$TargetUser]

# copy file to $TargetHost