0

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

xio
  • 630
  • 5
  • 11
  • 2
    [Hashtable](https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-hashtable?view=powershell-7.1) seems pretty good for the task at hand :) – Santiago Squarzon May 25 '21 at 13:41

1 Answers1

1

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Thank you so much, that is amazing! That has solved my issue. Honestly, wish I could buy you a beer! – Christopher Retford May 25 '21 at 14:07
  • @ChristopherRetford Maybe you'll get the chance one day ^_^ For now, all I ask is you consider marking my answer "accepted" by clicking the checkmark on the left :-) – Mathias R. Jessen May 25 '21 at 14:11
  • It's the least I can do friend. Thank you again so much. I am very grateful. Honestly PS has opened my world up with the things it can do and I am learning so so much from people like yourselves! – Christopher Retford May 25 '21 at 15:03