itye1970
itye1970

Reputation: 1995

how do you pass parameters into string variables in powershell

I am running a command to add machines to the domain and it all works ok.

I now want to take the values in $string1 from parameters values, is there a way of doing this?

$rg = "resourcegroup"
$machines = Get-AzureRmVM -ResourceGroupName $rg

$string1 ='{
  "Name" : "domain.local",
  "User": "domain.local\\domainadmin",
  "Restart" : "true",
  "Options" : "3",
}'

$string2 = '{"Password" : "@@@@@@@@@@@@@B"}'

$machines | ForEach { Set-AzureRmVMExtension -ResourceGroupName $rg
  -ExtensionType "JSONADDomainExtension" -Name "joindomain"
  -Publisher "Microsoft.Compute" -TypeHandlerVersion "1.0" -VMName $_.Name
  -Location "uk west" -SettingString $string1 -ProtectedSettingString $String2 }

Upvotes: 0

Views: 93

Answers (3)

Joey
Joey

Reputation: 354854

Build a custom object and convert it to JSON. That way you stay clear of any and all escaping issues and since the input is actual PowerShell code, it's trivial to change any part of the object:

[pscustomobject] @{
  Name = 'domain.local'
  User = 'domain.local\domainadmin'
  Restart = 'true'
  Options = '3'
} | ConvertTo-Json

yields the following:

{
    "Name":  "domain.local",
    "User":  "domain.local\\domainadmin",
    "Restart":  "true",
    "Options":  "3"
}

Upvotes: 1

henrycarteruk
henrycarteruk

Reputation: 13227

Just concatenate the strings and parameter variables:

param (
    [string]$name
)


$string1 ='{
  "Name" : "' + $name +'",
  "User": "domain.local\\domainadmin",
  "Restart" : "true",
  "Options" : "3",
}'

Upvotes: 0

lit
lit

Reputation: 16266

The trick appears to be to escape the curly braces by doubling them.

$string1 ='{{
  "Name" : "{0}",
  "User": "{1}",
  "Restart" : "{2}",
  "Options" : "{3}"
}}' -f 'domain.local', 'domain.local\\domainadmin', 'true', '3'

Upvotes: 0

Related Questions