如何根据 azure 命令的输出在 powershell 中拆分字符串
how to split a string in powershell based on output from azure command
我有一个正在尝试编写的 powershell 脚本。我需要从控制台获取一些输入/输出并将其通过管道传输到拆分命令中,但我不知道如何操作。
我是 运行 一个 azure cli 命令...列出一堆资源。我需要提取存储帐户的名称。
这是一些示例输出:
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
这是我现在用来查找存储帐户的 powershell 命令:
az resource list -g jjResourceGrp -o table | Select-String -Pattern "storageAccounts"
但我真正需要的是从该行中提取“asdf1234-storage”。
任何帮助将不胜感激。
正如Ash指出的:
最好使用 PowerShell 命令来输出 您可以对其属性进行操作的对象,在本例中需要安装 Az
PowerShell module (Install-Module Az
), which then allows you to call Get-AzStorageAccount
.
如果您正在与 外部程序 交互,例如 az
CLI,您必须处理with text (string) 输出,这使得后续处理复杂化:
下一个最佳选择是处理外部程序的结构化文本输出格式,如果可用,这样作为 CSV 或 JSON;事实上,正如 Ash 也指出的那样,az
CLI 的 default output format is JSON, so you could omit -o table
and process the output further with ConvertFrom-Json
除此之外,需要基于 文本解析 ,通常基于 regexes, such as via the -replace
and -split
运算符。
回答问题(因为文本解析非常有趣):
switch
语句结合其 -Regex
开关提供了一个简洁的解决方案:
switch -Regex (az resource list -g jjResourceGrp -o table) {
'^(\w+).*\bstorageAccounts\b' {
$Matches[1]; break
}
}
我有一个正在尝试编写的 powershell 脚本。我需要从控制台获取一些输入/输出并将其通过管道传输到拆分命令中,但我不知道如何操作。
我是 运行 一个 azure cli 命令...列出一堆资源。我需要提取存储帐户的名称。 这是一些示例输出:
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
这是我现在用来查找存储帐户的 powershell 命令:
az resource list -g jjResourceGrp -o table | Select-String -Pattern "storageAccounts"
但我真正需要的是从该行中提取“asdf1234-storage”。 任何帮助将不胜感激。
正如Ash指出的:
最好使用 PowerShell 命令来输出 您可以对其属性进行操作的对象,在本例中需要安装
Az
PowerShell module (Install-Module Az
), which then allows you to callGet-AzStorageAccount
.如果您正在与 外部程序 交互,例如
az
CLI,您必须处理with text (string) 输出,这使得后续处理复杂化:下一个最佳选择是处理外部程序的结构化文本输出格式,如果可用,这样作为 CSV 或 JSON;事实上,正如 Ash 也指出的那样,
az
CLI 的 default output format is JSON, so you could omit-o table
and process the output further withConvertFrom-Json
除此之外,需要基于 文本解析 ,通常基于 regexes, such as via the
-replace
and-split
运算符。
回答问题(因为文本解析非常有趣):
switch
语句结合其 -Regex
开关提供了一个简洁的解决方案:
switch -Regex (az resource list -g jjResourceGrp -o table) {
'^(\w+).*\bstorageAccounts\b' {
$Matches[1]; break
}
}