2017-08-31 262 views
1

我无法理解如何追加或对象更新数据如何在Powershell中添加/更新多深度对象?

所以可以说我有看起来像这样下面我要在架构添加到对象的架构在运行此命令

后数据的对象
$testdata | Format-Custom -Property * -Depth 6 
 
class PSCustomObject 
{ 
    sessions = 
    [ 
     class PSCustomObject 
     { 
     type = current 
     generated = 2017-08-31T09:02:55.251Z 
     windows = 
      [ 
      class PSCustomObject 
      { 
       id = 770 
       incognito = False 
       tabs = 
       [ 
        class PSCustomObject 
        { 
        active = True 
        id = 771 
        incognito = False 
        title = Subscriptions - YouTube 
        url = https://www.youtube.com/feed/subscriptions 
        windowId = 770 
        } 
        class PSCustomObject 
        { 
        active = False 
        id = 776 
        incognito = False 
        title = Overly Sarcastic Productions - YouTube 
        url = https://www.youtube.com/user/RedEyesTakeWarning/videos 
        windowId = 770 
        } 

       ] 

      } 
      class PSCustomObject 
      { 
       id = 773 
       incognito = False 
       tabs = 
       [ 
        class PSCustomObject 
        { 
        active = False 
        id = 774 
        incognito = False 
        title = Technology - Google News 
        url = https://news.google.com/news/headlines/section/topic/TECHNOLOGY?ned=us&hl=en 
        windowId = 773 
        } 
        class PSCustomObject 
        { 
        active = False 
        id = 806 
        incognito = False 
        title = Microsoft PowerShell Is a Hot Hacker Target, But Its Defenses Are Improving | WIRED 
        url = https://www.wired.com/story/microsoft-powershell-security/ 
        windowId = 773 
        } 
        ... 
       ] 
      } 
      ] 
     } 
    ] 
} 

所以可以说,我想一个新的选项卡添加到窗户与ID 和新选项卡的冠军雅虎网址https://yahoo.comID

我怎么会只是增加只是新进入的标签,而无需重新创建整个对象?

+0

请退后一步,描述您尝试解决的实际问题,而不是您认为的解决方案。 –

+0

那么通常当你追加说......就像一个数组或哈希,你使用'+ ='或'$ hash.add(something,$ something)',我不知道如何添加一个数据对象特殊的对象...因为我不能去'($ testdata.sessions.windows.Where({$ _。id -eq 770})。tabs)+ = $ newtabobject',因为这似乎不起作用,当我尝试它时,尽管它与其他选项卡对象的设置相同 – Ziabytes

+0

如何创建'$ testdata'对象? – Persistent13

回答

0

所以这不是一个真正的答案,但更像是一个工作。

我自己不明白如何修改Powershell中的对象,就像你想要的那样。通常一个简单的+=通常适用于大多数事情。

但是,对于您的问题,似乎试图添加具有特定ID的SPECIFIC对象中的键值对的对象直接向上+=是行不通的,因为您试图解析你的方式。你只会得到属性没有找到什么的愚蠢错误。

我这样做,如果它是一个静态列表和订单/位置WONT在我更新它之前更改,将获得我希望添加到的特定对象的INDEX。然后,根据索引,将数据对象/散列的一个简单的+=执行到您希望修改的对象。

类似如下:

首先,你的键值对准备新对象或哈希。

$newhash = @{} 
$newhash.Add("title","yahoo") 
$newhash.Add("url", "https://yahoo.com") 
$newhash.Add("id", "9001") 

接下来,找到你要修改的对象的索引/插件与.IndexOf(),喜欢你的id 770

$position = $testdata.sessions.windows.id.IndexOf(770) 

这应该告诉你在什么位置对象的对象列表与特定ID为是

现在,毫不夸张地说,简单的+=到您想要添加/修改的特定窗口的选项卡。

$testdata.sessions.windows[$position].tabs += $newhash 

如果你感到困惑,用[]东西表示选择后的名单上的位置,像[0]暂时先等等等等。

这应该是它。

注意:在更新数据之前更新数据以及在修改数据之前更改位置的情况下,此功能不起作用。

我意识到这可能不是你正在寻找,但仍然。

希望这会有所帮助。

+1

非常感谢。你是正确的,它并不是我正在寻找的东西,但它有帮助。所以从某种意义上说,我的问题得到了解决,而不是我喜欢的方式。 – Ziabytes