Home > Mobile >  Create Array of Arrays in powershell
Create Array of Arrays in powershell

Time:07-09

Greeting!

I am trying a script to create multiple service. For each services I have created an array for each services and again I created an array including arrays one created for the service like below.

  $Service1 = @{
  Name = "TestService"
  BinaryPathName = '"C:\WINDOWS\System32\example.exe -k netsvcs"'
  DependsOn = "NetLogon"
  DisplayName = "Test Service"
  StartupType = "Manual"
  Description = "This is a test service."
}

$Service2 = @{
  Name = "TestService"
  BinaryPathName = '"C:\WINDOWS\System32\example1.exe -k netsvcs"'
  DependsOn = "NetLogon"
  DisplayName = "Test Service1"
  StartupType = "Manual"
  Description = "This is a test service1."
}

$services = @("@Service1","@Service2")

When I try to call array

$($services[1])

it is giving output as

@Service1

I guess it is not providing the value required to create service. Can I get a expert advice here it would be helpful.

New-Service @Service1

CodePudding user response:

Just try :

  $Service1 = @{
  Name = "TestService"
  BinaryPathName = '"C:\WINDOWS\System32\example.exe -k netsvcs"'
  DependsOn = "NetLogon"
  DisplayName = "Test Service"
  StartupType = "Manual"
  Description = "This is a test service."
}

$Service2 = @{
  Name = "TestService"
  BinaryPathName = '"C:\WINDOWS\System32\example1.exe -k netsvcs"'
  DependsOn = "NetLogon"
  DisplayName = "Test Service1"
  StartupType = "Manual"
  Description = "This is a test service1."
}

$services = @($Service1,$Service2)

Then first index is zero :

$services[0]
$services[1]

CodePudding user response:

I think what you want is simply this:

$Services = @{
  Name = "TestService"
  BinaryPathName = '"C:\WINDOWS\System32\example.exe -k netsvcs"'
  DependsOn = "NetLogon"
  DisplayName = "Test Service"
  StartupType = "Manual"
  Description = "This is a test service."
},
@{
  Name = "TestService"
  BinaryPathName = '"C:\WINDOWS\System32\example1.exe -k netsvcs"'
  DependsOn = "NetLogon"
  DisplayName = "Test Service1"
  StartupType = "Manual"
  Description = "This is a test service1."
}

Now you have an array of Hashtables, each defining the service. Just use them in a loop like

foreach ($service in $Services) {
    New-Service @$service
}

or if you like individually (for example just item 1)

New-Service @Services[1]
  • Related