我是Powershell的新手。我正在尝试创建一个脚本,该脚本可以使用包含我需要的属性的对象在JSON中生成本地应用程序设置。
我有一个名为"Process-Section“的函数,它接受一个sectionObject。节对象可以包含单个值,也可以包含另一个节。
如果对象包含另一个节,它应该调用自己,将另一个节作为参数传递(递归)。如果该部分中没有节,它应该只调用一个名为"Process-SingleConfig“的方法。
我的问题是,当我达到我的对象的最大深度时,你知道当没有更多的部分和只是值时,它仍然声明属性"sectionObject.sectionName“不是空的或空的,因此它命中"if块”,并试图用一个不存在的属性调用自己,但实际上它应该转到"else-block“。
你可以在下面看到这个函数:
function Process-Section
{
param
(
[object]$sectionObject
)
$result = New-Object -TypeName object
Write-Host "SectionObj: $($sectionObject)"
Write-Host "Section Values Count: $($sectionObject.sectionValues.Count)"
Write-Host "Is Section Name in this sectionObject null? $([string]::IsNullOrEmpty($sectionObject.sectionName))"
Write-Host "Is Section Name in this sectionObject empty? $('' -eq $sectionObject.sectionName)"
# Recursive section processing
if(-NOT [string]::IsNullOrEmpty($sectionObject.sectionName)){
Write-Host "Running through section: $($sectionObject.sectionName)"
foreach($item in $sectionObject.sectionValues.GetEnumerator()){
Write-Host $item.localSettingsKey
Write-Host $item.value
}
$nestedSectionObject = Process-Section -sectionObject $sectionObject.sectionValues
$result | Add-Member -MemberType NoteProperty -Name $sectionObject.sectionName -Value $nestedSectionObject
} else {
Write-Host "Section object that will be processed one config by one"
Write-Host $sectionObject
foreach($sectionConfig in $sectionObject)
{
$configToAdd = Process-SingleConfig -config $sectionConfig
$result | Add-Member -MemberType NoteProperty -Name $configToAdd.key -Value $configToAdd.value
}
}
Write-Host "Result $($result)"
return $result;
}在第一次运行时,看起来还可以

但是当我可以再次使用$sectionObject.sectionValues作为参数时,它实际上应该没有任何名称,但它仍然声称该名称不是空的,这就是事情变得奇怪的地方。

新的调用堆栈是否引用了前一个调用堆栈中的对象?
下面这几行似乎是造成麻烦的原因:
$nestedSectionObject = Process-Section -sectionObject $sectionObject.sectionValues
$result | Add-Member -MemberType NoteProperty -Name $sectionObject.sectionName -Value $nestedSectionObject 发布于 2021-02-03 19:54:38
事实证明,if(-NOT [string]::IsNullOrEmpty($sectionObject.sectionName)){不是检查对象是否具有某个属性以及它是否为空的最佳方法。我所要做的是使用:
if($null -ne ($sectionObject | Get-Member -MemberType NoteProperty -Name "sectionName"))https://stackoverflow.com/questions/66023611
复制相似问题