Reputation: 105
I am trying use Read-Host -Prompt to fill out multiple server names and user account names, and then pass those into the invoke-command to complete the task - which is to make someone local admin. I am unable to figure out why PowerShell throws me this error: "One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.".
In addition, I am also getting the error:
"Add-LocalGroupMember : Object reference not set to an instance of an object."
Code example below:
if ($OptPrompt -eq 1) {
$prompt1 = Read-Host -Prompt 'Test Accounts'
$prompt1.Split(",")
$prompt1_1 = Read-Host -Prompt 'Test Servers'
$prompt1_1.Split(",")
Invoke-Command -ComputerName $prompt1_1 -ScriptBlock {Add-LocalGroupMember -Group 'Administrators' -Member $Using:prompt1}
}
More info:
Servers are online
Servers have "-" in them, for example, "Server-22-test"
Servers are responding to ping (hostname and IP address)
Using Invoke-Command on its own works, but not inside the function
There is no firewall or security blocking the account(s) in question
Thank you for your help.
Upvotes: 0
Views: 336
Reputation: 25001
It appears that you are expecting $prompt1
and $prompt1_1
to contain comma-delimited names. By using Read-Host
to populate the variables, they will be type String
. You will need to rely on users to enter the comma separators manually with your code. With that said, executing the .Split()
method on a String object does not update the String object. You must either update the variable assignment or pass the method outputs as expressions into Invoke-Command
.
# Method 1: Reassigning Variable Before Invoke-Command
if ($OptPrompt -eq 1) {
$prompt1 = Read-Host -Prompt 'Test Accounts'
$prompt1 = $prompt1.Split(",")
$prompt1_1 = Read-Host -Prompt 'Test Servers'
$prompt1_1 = $prompt1_1.Split(",")
Invoke-Command -ComputerName $prompt1_1 -ScriptBlock {Add-LocalGroupMember -Group 'Administrators' -Member $Using:prompt1}
}
# Method 2: Passing Expressions into Invoke-Command
if ($OptPrompt -eq 1) {
$prompt1 = Read-Host -Prompt 'Test Accounts'
$prompt1_1 = Read-Host -Prompt 'Test Servers'
Invoke-Command -ComputerName $prompt1_1.Split(",") -ScriptBlock {Add-LocalGroupMember -Group 'Administrators' -Member ($using:prompt1).Split(",") }
}
The advantage of using expressions is your original variables remain unchanged.
Upvotes: 3