gpt4 book ai didi

powershell - 替换/重命名对象属性名称

转载 作者:行者123 更新时间:2023-12-05 01:38:38 25 4
gpt4 key购买 nike

如果 dns 解析成功,我需要将“ip-netmask”替换为“fqdn”。

此脚本将用于替换配置文件中的值。

如果解析了DNS,我需要将“ip-netmask”的属性名称更改为“fqdn”,并将新的dns 值存储在其下。该脚本解析 DNS 并仅在成功时更新 ip-netmask,如果成功,还会添加具有 DNS 值的 fqdn 属性。

似乎我在那里,但我无法将 ip-netmask 重命名为 fqdn,或者只是删除 ip-netmask 属性而不使我的 fqdn 属性为空

来自原始的json输入


@'
{
"entry":[
{
"@name":"31.170.162.203",
"ip-netmask":"31.170.162.203",
"description":"test1"
},
{
"@name":"37.193.217.222",
"ip-netmask":"37.193.217.222",
"description":"test2"
},
{
"@name":"46.17.63.169",
"ip-netmask":"46.17.63.169",
"description":"test3"
}
]
}

$a = Get-Content 'C:\Users\e\Desktop\puttytest1.json' | ConvertFrom-Json



$a.entry | ForEach-Object {

if ($namehost = (Resolve-DnsName $_.'ip-netmask').namehost) {

$_.'ip-netmask' = $namehost

$_ | Add-Member -MemberType AliasProperty -Name fqdn -Value ip-netmask

}
}

$newjson = $a | ConvertTo-Json

$newjson

输出


{

"entry": [

{

"@name": "31.170.165.68",

"ip-netmask": "31.170.165.68",

"description": "Test1"

},

{

"@name": "31.170.162.203",

"ip-netmask": "31.170.162.203",

"description": "test2"

},

{

"@name": "37.193.217.222",

"ip-netmask": "l37-193-217-222.novotelecom.ru",

"description": "test3",

"fqdn": "l37-193-217-222.novotelecom.ru"

}

]

}

最佳答案

您不应尝试重命名现有属性,而应将其删除并将新的 NoteProperty 添加到对象,如下所示:

$newjson = $a.entry | ForEach-Object {
if ($namehost = (Resolve-DnsName $_.'ip-netmask').namehost) {
# remove the 'ip-netmask' property
$_.PSObject.Properties.Remove('ip-netmask')
# add a new NoteProperty 'fqdn'
$_ | Add-Member -MemberType NoteProperty -Name 'fqdn' -Value $namehost
}
} | ConvertTo-Json

但是,我相信您使用错误的方法从 IP 地址检索 fqdn。这不应该是:

$newjson = $a.entry | ForEach-Object {
if ($namehost = [System.Net.Dns]::GetHostByAddress($($_.'ip-netmask')).HostName) {
# remove the 'ip-netmask' property
$_.PSObject.Properties.Remove('ip-netmask')
# add a new NoteProperty 'fqdn'
$_ | Add-Member -MemberType NoteProperty -Name 'fqdn' -Value $namehost
}
} | ConvertTo-Json

希望对你有帮助


根据您的评论,属性的显示顺序对您很重要。

要维护该顺序,请使用

$newjson = $a.entry | ForEach-Object {
if ($namehost = (Resolve-DnsName $_.'ip-netmask').namehost) {
# output a new object with properties ordered like you want them to be
$_ | Select-Object '@name', @{Name = 'fqdn'; Expression = {$namehost}}, 'description'
}
else {
# output the object unchanged
$_
}
} | ConvertTo-Json

关于powershell - 替换/重命名对象属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537372/

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