Reputation: 15660
I have a powershell script that i'm trying to write. I need to take some input / output from the console and pipe it into a split command but I don't know how.
I'm running an azure cli command... to list a bunch of resources. and I need to extract the name of the storage account. Here's some sample output:
Name ResourceGroup Location Type
------------------ ------------- ------------ ----------
asdf1234-insights jjResourceGrp eastus microsoft.insights/components
asdf1234-storage jjResourceGrp eastus Microsoft.Storage/storageAccounts
asdf1234 jjResourceGrp eastus Microsoft.Web/serverFarms
asdf1234 jjResourceGrp eastus Microsoft.Web/sites
This is the powershell command I'm using right now to find just the storage Account:
az resource list -g jjResourceGrp -o table | Select-String -Pattern "storageAccounts"
But what I really need is to extract the "asdf1234-storage" from that line. Any help would be appreciated.
Upvotes: 3
Views: 866
Reputation: 437833
As Ash has pointed out:
It is always preferable to use PowerShell commands that output objects whose properties you can operate on, which in this case requires installing the Az
PowerShell module (Install-Module Az
), which then allows you to call Get-AzStorageAccount
.
If you're interacting with external programs, such as the az
CLI, you're of necessity dealing with text (string) output, which complicates subsequent processing:
The next best option is to deal with an external program's structured text output format, if available, such as CSV or JSON; indeed, as Ash also points out, the az
CLI's default output format is JSON, so you could omit -o table
and process the output further with ConvertFrom-Json
Absent that, text parsing based, typically based on regexes, such as via the -replace
and -split
operators, are required.
To answer the question as asked (because text parsing is so much fun):
The switch
statement combined with its -Regex
switch offers a concise solution:
switch -Regex (az resource list -g jjResourceGrp -o table) {
'^(\w+).*\bstorageAccounts\b' {
$Matches[1]; break
}
}
Upvotes: 3