gpt4 book ai didi

azure - Powershell ForEach-对象 : You cannot call a method on a null-valued expression

转载 作者:行者123 更新时间:2023-12-02 06:54:37 25 4
gpt4 key购买 nike

我正在尝试提取 SystemOwner 和 TechnicalOwner 的标签值。但是我收到错误“ForEach-Object:您无法在空值表达式上调用方法”我已经知道“$Tags = $RG.Tags”可能是问题所在,因为运行此变量不会给我任何结果。那么如何获取资源组标签呢?

$RGs = (Get-AzResourceGroup).ResourceGroupName
ForEach-Object $RG in $RGs
{
# Get email address value for each SystemOwner and TechnicalOwner Tag in the RG
$Tags = $RG.Tags
$TO = ($Tags.GetEnumerator() | Where-Object {$_.Key -eq "Technical*"}).value
If ($TO)
{
if ($TO.Value -ne $null) {
Write-Host "Technical Owner Found in the Resource Group, building an Array"
$contactemailadress += $TO.Value
}
}
$SO = $Tags.GetEnumerator() | Where-Object {$_.Key -eq "SystemOwner"} #looking for Resource Group tag Names that have a space in the name
If ($SO)
{
if ($SO.Value -ne $null) {
Write-Host "System Owner Found in the Resource Group, building an Array"
$contactemailadress += $SO.Value
}
}
}

最佳答案

我认为你可以做这样的事情:

$contactemailadress = @()
$RGs = Get-AzResourceGroup
$RGs | ForEach-Object {
# Get email address value for each SystemOwner and TechnicalOwner Tag in the RG
$Tags = $_.Tags

If ($Tags -and $Tags['TechnicalOwner'])
{
Write-Host "Technical Owner Found in the Resource Group, building an Array"
$contactemailadress += $Tags['TechnicalOwner']
}

If ($Tags -and $Tags['SystemOwner'])
{
Write-Host "System Owner Found in the Resource Group, building an Array"
$contactemailadress += $Tags['SystemOwner']
}
}

您遇到的主要问题是 (Get-AzResourceGroup).ResourceGroupName 返回资源组名称 - 但是,为了返回标记,您需要完整的对象。

您可以通过检查正在运行的 Get-AzResourceGroup 命令的属性来证明这一点:

(Get-AzResourceGroup -Name resource_group_name).ResourceGroupName | Get-Member -Type Property

TypeName: System.String

Name MemberType Definition
---- ---------- ----------
Length Property int Length {get;}

如您所见,此命令只有一个属性 - length,这对您的脚本目的没有用处。

如果您运行此命令,您将获得具有所有属性的完整对象:

Get-AzResourceGroup -Name resource_group_name | Get-Member -Type Property

TypeName: Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels.PSResourceGroup

Name MemberType Definition
---- ---------- ----------
Location Property string Location {get;set;}
ManagedBy Property string ManagedBy {get;set;}
ProvisioningState Property string ProvisioningState {get;set;}
ResourceGroupName Property string ResourceGroupName {get;set;}
ResourceId Property string ResourceId {get;set;}
Tags Property hashtable Tags {get;set;}
TagsTable Property string TagsTable {get;}

您可以使用 foreachForEach-Object,两者都应该有效,但使用后者时,您可以使用 $_< 查询循环内的变量 表示法。

最后,在您的脚本中似乎有一些不必要使用的变量(但我不知道您以后是否需要它们),例如 $TO 和两个 if 语句或更少执行相同的操作(即 If ($SO)if ($SO.Value -ne $null))。

关于azure - Powershell ForEach-对象 : You cannot call a method on a null-valued expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73773710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com