I am creating a PowerShell script using Convert To-JSON cmd and i achieved that using below
$body = @{
devices = @(
@{
credentials = @(
@{
label = 'username'
value = 'myname'
sensitive = 'false'
},
@{
label = 'Password'
value = 'Password@!'
sensitive = 'true'
}
)
services = @(
@{
name = 'RDP'
url = 'https://192.168.1.6/?pauth=[proxy_token]&data=[connection:username-rdp]'
instructor = 'false'
}
connections = @(
@{
id = 'myname-rdp'
protocol = 'rdp'
hostname = "192.168.1.6"
port ='3389'
}
)
Parameters = @(
@{
name = 'username'
value = 'myname'
},
@{
name = 'password'
value = 'Password@!'
}
)
}
)
}
i am converting the above powershell to JSON File($body | ConvertTo-Json -Depth 4
) and i would like to replace pass the arguments for the Username and IP Address and store it with the username.json every time while converting to JSON.
i have tried the Read-host to get the input from the user but i am facing difficulty to pass that input before printing the output.
CodePudding user response:
For the IP address, you can set the new value by defining the parameter using standard dot-notation.
In the case of username
, because Parameters
is an array with duplicate object names, doing $body.devices.Parameters.name
would return both the username and password objects, so you can filter the array to only select the object where the name
is username
$inputUsername = Read-Host "Input Username"
$inputIpAddress = Read-Host "Input IP address"
( $body.devices.Parameters | Where-Object { $_.name -eq 'username' } ).value = $inputUsername
$body.devices.connections.hostname = $inputIpAddress
$body | ConvertTo-Json -Depth 4
CodePudding user response:
As an interpreted language, PowerShell allows you to construct literals based on values that are determined at runtime.
Therefore, simply place your hashtable literal (@{ ... }
) after your Read-Host
calls, and reference the variables in which you store the Read-Host
responses in that literal.
A simplified example:
# Simulate two Read-Host calls (hard-code sample values).
$foo = 42
$bar = 'hi'
# Now define the hashtable literal and reference the variables assigned to above.
@{
devices = @{
foo = $foo
bar = $bar
}
}
Piping the above to ConvertTo-Json -Depth 4
yields:
{
"devices": {
"foo": 42,
"bar": "hi"
}
}
Note how the values of $foo
and $bar
were incorporated. You could even use the same technique in a loop, provided the hashtable literal is also in the loop body (after setting the variables it references).