0
votes

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!

1
can you post the output of $ComputerNameArray? have you tried creating the array like this for testing: `$ComputerNameArray = "computername1","computername2"?Guenther Schmitz
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.AdminOfThings
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 optionmrt
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.AdminOfThings
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.AdminOfThings

1 Answers

1
votes

This works for me:

Invoke-Command $ComputerNameArray { $env:computername }