【发布时间】:2019-07-12 07:54:47
【问题描述】:
我正在尝试使用 CSV 文件中的标签从 azure 标记我所有正在运行的 VM,但是从 VSCode PowerShell 核心终端运行时我的 PowerShell 脚本失败。
我仔细检查并设置了正确的活动订阅(我们有多个租户和订阅),但输出显示它找不到我的资源组(它们肯定在那里)。
Enable-AzureRmAlias
$csv = import-csv "C:\Users\popes\Desktop\Jedox\Powershell scripts\Tagging\Tagging.csv"
$csv | ForEach-Object {
# Retrieve existing tags
$tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM).Tags
# Define new value pairs from CSV
$newTags = @{
company = $_.Company
dns = $_.DNS
type = $_.Type
CN = $_.CN
}
# Add new tags to existing set (overwrite conflicting tag names)
foreach($CN in $newTags.Keys){
$tags[$_] = $newTags[$_]
}
# Update resource with new tag set
Set-AzResource -ResourceGroupName $_.RG -Name $_.VM -Tag $tags -ResourceType "Microsoft.Compute/virtualMachines"
}
输出:
Get-AzResource : Resource group 'machine774_rg' could not be found.
At line:3 char:14
+ ... $tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Mi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzResource], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
Cannot index into a null array.
At line:15 char:9
+ $tags[$_] = $newTags[$_]
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
【问题讨论】:
-
好吧,首先:各种集成终端都是垃圾。其次,您能否验证您是否在正确的租户\sub 中并显示 get-azresourcegroup 的输出
-
如果我执行 az account show,它表明我在正确的订阅中。但是,如果我执行 get-azresourcegroup,它会显示来自默认订阅的 RG,而不是当前订阅。
-
您了解 az cli 和 az powershell 使用不同的方式进行身份验证吗?
-
好的,使用正确的命令登录似乎已经解决了缺少 rg 的问题。但是,我在运行脚本时仍然遇到一些奇怪的错误:
Unable to index into an object of type "System.Collections.Generic.Dictionary'2[System.String,System.String]". At line:15 char:9 + $tags[$_] = $newTags[$_] + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : CannotIndex -
好的,我设法通过删除会强制覆盖新标签的代码使其工作。感谢您的帮助@Joy Wang
标签: azure powershell visual-studio-code