0

I am wondering how to accomplish the following and hope you can help:

I want to execute several tasks on different computers by providing a array of computernames using

Invoke-Command -ComputerName $ComputerNameArray -ScriptBlock { ...}

Inside the scriptblock, I want to access the current ComputerName (not the whole array).

How is this possible?

I tried enclosing the Invoke-Command within a foreach loop, something like this:

foreach ($Computer in $ComputerNameArray)
{
 Invoke-Command-ComputerName $Computer -ScriptBlock { ...}
}

which works, this way I can access the current ComputerName with $env:Computer but as the foreach isn't necessary here, I want to get rid of it.

Any ideas?

Thanks all!

6
  • can you post the output of $ComputerNameArray? have you tried creating the array like this for testing: `$ComputerNameArray = "computername1","computername2"? Commented Feb 5, 2020 at 14:08
  • Inside of the script block, you can use $PSSenderInfo.ConnectionString -replace '^.*?//([^:]+).*','$1' to see the array item sent to the command. This requires a successful connection to the computer. I don't see why $env:computername isn't sufficient in both cases. Commented Feb 5, 2020 at 14:18
  • Declaration is: string[]]$ComputerNameArray=@( "server1", "server2") $env:ComputerName is not working, because there is no env variable called ComputerName but only ComputerNameArray. The env variable is only available if Invoke-Command is executed inside a loop. I want to get rid of the foreach loop for some elegance and code readability - sorry, regex is not an option Commented Feb 5, 2020 at 14:26
  • If you use the -AsJob parameter, you can see the array item in the location property that was used for that particular job. (Get-Job).ChildJobs.Location. Commented Feb 5, 2020 at 14:28
  • 1
    If the goal is to use the current item of the array outside of the -Scriptblock parameter and in another command, just use the loop. If the goal is to use the current array item inside of -Scriptblock, then $env:computername is an environment variable for that session on a Windows system and it is not necessarily the exact string you passed in. Commented Feb 5, 2020 at 14:32

1 Answer 1

1

This works for me:

Invoke-Command $ComputerNameArray { $env:computername }
Sign up to request clarification or add additional context in comments.

Comments

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.