我有一个正在尝试编写的 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”。
任何帮助,将不胜感激。
As Ash https://stackoverflow.com/users/9164015/ash已指出:
-
总是最好使用电源外壳输出的命令您可以对其属性进行操作的对象,在这种情况下需要安装Az https://www.powershellgallery.com/packages/Az/6.0.0PowerShell 模块(Install-Module Az
),然后您可以调用Get-AzStorageAccount https://learn.microsoft.com/en-us/powershell/module/az.storage/get-azstorageaccount.
-
如果您正在与外部程序, 如那个az
CLI,你必须处理text(字符串)输出,这使后续处理变得复杂:
-
下一个最佳选择是处理外部程序的结构化的文本输出格式(如果可用),例如 CSV 或 JSON;事实上,正如阿什还指出的那样,az
CLI's 默认输出格式 https://learn.microsoft.com/en-us/cli/azure/format-output-azure-cli isJSON,所以你可以省略-o table
并进一步处理输出ConvertFrom-Json https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-json
-
如果没有那个,文本解析基于,通常基于regexes https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Regular_Expressions,例如通过-replace https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Comparison_Operators#replacement-operator and -split https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Split操作员,是必需的。
回答问题as asked(因为文本解析非常有趣):
The switch https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Switch声明与其相结合-Regex
switch 提供了一个简洁的解决方案:
switch -Regex (az resource list -g jjResourceGrp -o table) {
'^(\w+).*\bstorageAccounts\b' {
$Matches[1]; break
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)