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!
$ComputerNameArray
? have you tried creating the array like this for testing: `$ComputerNameArray = "computername1","computername2"? – Guenther Schmitz$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$env:ComputerName
is not working, because there is no env variable called ComputerName but only ComputerNameArray. The env variable is only available ifInvoke-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 – mrt-AsJob
parameter, you can see the array item in the location property that was used for that particular job.(Get-Job).ChildJobs.Location
. – AdminOfThings-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