I have a script which invokes a session on remote computer and run a script.
$pw = convertto-securestring -AsPlainText -Force -String '$(PWD_vSphere_AdminUser)'
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist ".\Administrator",$pw
Invoke-Command -Credential $Cred -ComputerName 'testcomputer' -FilePath "./addvm.ps1"
This works fine. Now I have to run it on multiple computers. I want to read -ComputerName values from a tfvars file (json format). where name = "testcomputer" occurring multiple times. I want to read this "name" value from tfvars file (json format) and run my script for each "name" value.
{
"vm": [
{
"testcomputer": [
{
"memory": "4096",
"name": "testcomputer",
"time_zone": "020"
}
],
"testcomputer1": [
{
"memory": "4096",
"name": "testcomputer1",
"time_zone": "020"
}
],
"testcomputer2": [
{
"memory": "4096",
"name": "testcomputer2",
"time_zone": "020"
}
]
}
]
}
I have read this Powershell retrieving a variable from a text file but that dosen`t solve much about occurrence.
CodePudding user response:
If what you share is really the input you will get literally, one way to deal with it would be to use Regex, but if can somehow input that as an object, either JSON or XML or whatever that can be read and properly converted in to an object, you should do that instead of Regex.
As of regex, reading from literally the input you showed , you can do something like this :
$inputVar = @"
vm = {
"testcomputer" = {
name = "testcomputer"
memory = "4096"
time_zone = "020"
}
"testcomputer1" = {
name = "testcomputer1"
memory = "4096"
time_zone = "020"
}
"testcomputer2" = {
name = "testcomputer2"
memory = "4096"
time_zone = "020"
}
}
"@
#the matching pattern.
$regexFormat = '(?<=name = ").[^"]*'
#Grab only the matching pattern items.
$computerList = [regex]::Matches($inputVar, $regexFormat) | ForEach-Object { $_.value }
foreach ($computer in $computerList) {
$pw = convertto-securestring -AsPlainText -Force -String '$(PWD_vSphere_AdminUser)'
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist ".\Administrator", $pw
Invoke-Command -Credential $Cred -ComputerName $computer -FilePath "./addvm.ps1"
}
I have made a literally input with the $inputVar
just to show the example, and then you can do foreach loop to run your code for each computer.