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

1
  • 2
    Hashtable seems pretty good for the task at hand :) Commented May 25, 2021 at 13:41

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, that is amazing! That has solved my issue. Honestly, wish I could buy you a beer!
@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 :-)
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.