You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中修改$tempStuff为何会影响$objectFromAPIStuff及深层对象?

PowerShell对象修改同步问题分析与解决

问题原因

你遇到的是PowerShell中引用类型赋值的特性:
从ConvertFrom-Json生成的对象属于引用类型(PSCustomObject),这类对象的变量存储的是内存中对象的地址,而非对象本身。

你的代码里:

  1. $objectFromAPIStuff = $stuffFromAPI.item[0] —— 让$objectFromAPIStuff指向$stuffFromAPI.item[0]对应的内存对象
  2. $tempStuff = $objectFromAPIStuff —— 让$tempStuff也指向同一个内存对象
  3. 修改$tempStuff.ipAddress时,本质是直接修改内存中这个共享对象的属性,所以所有指向它的变量($objectFromAPIStuff、$stuffFromAPI.item[0])都会同步看到变化。

解决方法

要修改属性且不影响原对象,需要创建原对象的独立副本(深拷贝),以下是两种常用方式:

方式1:JSON序列化反序列化(通用便捷)

利用JSON的序列化和反序列化生成全新对象,适合大多数复杂结构:

# 替换原代码中的$tempStuff = $objectFromAPIStuff
$tempStuff = $objectFromAPIStuff | ConvertTo-Json -Depth 10 | ConvertFrom-Json

注意:-Depth参数要设置为足够大的值,确保对象的嵌套结构能被完整序列化。

方式2:手动创建新对象(适合简单结构)

如果对象属性不多,可以手动构建新的PSCustomObject并复制属性:

$tempStuff = [PSCustomObject]@{
    ipAddress = $objectFromAPIStuff.ipAddress
    # 按需添加其他需要复制的属性
}

修改后再执行代码,$tempStuff.ipAddress会变为10.0.0.1,而$objectFromAPIStuff和$stuffFromAPI.item[0]的ipAddress会保持原来的127.0.0.1。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 02:32:32