Home > OS >  Powershell - Select only one value from -out table
Powershell - Select only one value from -out table

Time:10-11

I need to select only one value from the out-table.

The code is:

az vm list-ip-addresses --name VMname --resource-group GroupName --out table

I get the result as below

VirtualMachine    PublicIPAddresses    PrivateIPAddresses
----------------  -------------------  --------------------
VMName            XX.XX.XX.XX          XX.XX.XX.XX

I want to select only the PublicIPAddresses value and extract it to csv.

TIA

CodePudding user response:

Output format option --output table (-o table) is meant for human-friendly (tabular) display rather than for programmatic processing.

It's better to use an output format based on structured text, such as JSON. Indeed, JSON is the default output format, so you can simply omit your --out table argument and use ConvertFrom-Json to parse the output and extract the values of interest:

# Outputs all public IP addresses contained in the JSON response.
# Since you're targeting only a *single* VM, the address(es) all refer to that VM.
$ip =
  (
   az vm list-ip-addresses --name VMname --resource-group GroupName |
     ConvertFrom-Json
  ).virtualMachine.network.publicIpAddresses.ipaddress

The structure of the JSON data returned is assumed to be the same as in this question.


Note that you can streamline the operation by using the --query parameter to perform a JMESPath query at the source, so that the only the values of interest are directly returned:

$ip =
  (az vm list-ip-addresses --query '[].virtualMachine.network.publicIpAddresses[].ipAddress' --name VMname --resource-group GroupName |
    ConvertFrom-Json)

Note:

  • You could simplify this further by using --output tsv, in which case you don't need the ConvertTo-Json call - see below.

According to this answer, the following shorter alternative that uses the az vm show sub-command - rather than az vm list-ip-addresses - works too:

$ip = 
  az vm show --show-details --resource-group --name vmName --query publicIps --output tsv

Note:

  • The above uses a different structured text format, TSV (tab-separated values), with --output tsv, which in this simple case obviates the need for post-processing on the PowerShell side:

    • The query returns one or more string values only, which in TSV format are output as-is, and, if there is more than one string, each on its own line. PowerShell captures this as either a single string or as an array of strings.

Extracting public IPs for multiple VMs (all VMs in a resource group):

# Returns the names and public IP addresses for all VMs in the
# given resource group, as [pscustomobject] instances with
# .name and .publicIds properties (the latter being an array).
$objects =
  az vm list-ip-addresses --query '[].virtualMachine.{ name: name, publicIps: network.publicIpAddresses[].ipAddress }' --resource-group GroupName |
    ConvertFrom-Json
  • Related