簡體   English   中英

在PowerShell cmdlet中導航父子關系

[英]Navigating parent-child relation in PowerShell cmdlet

假設我有像這樣的父子關系的對象:

public class Node
{
   public string Name { get; set; }
   public string Type { get; set; }
   public Node Parent { get; set; }
}

現在,我想創建一個支持如下語法的cmdlet:

Get-Node | where {$_.Type -eq "SomeType" -and $_.Parent.Name -eq "SomeName" }

這里,Parent屬性需要以某種方式引用管道中的另一個對象。 在PowerShell中甚至可以這樣嗎? 如果沒有,有哪些替代方案?

[編輯]如果我像上面這樣使用上面的類:

var root = new Node
{
    Name = "root",
    Type = "root",
    Parent = null
};
var nodeA = new Node
{
    Name = "A",
    Type = "node",
    Parent = root
}
WriteObject(root);
WriteObject(nodeA);

然后加載模塊並嘗試以下命令:

Get-MyNode | where {$_.Parent.Name = "root"}

我收到此錯誤:

Property 'Name' cannot be found on this object; make sure it exists and is settable.
At line:1 char:31
+ Get-MyNode | where {$_.Parent. <<<< Name = "root"}
    + CategoryInfo          : InvalidOperation: (Name:String) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound

我希望Parent屬性像真正的Node對象一樣引用管道中的另一個對象。

[編輯]此錯誤是由類定義中缺少的public關鍵字引起的。 添加關鍵字修復了問題並使示例正常工作。

我希望您的Get-Node cmdlet將返回一個完全填充的對象圖。 以下是使用XML的類似示例:

$xml = [xml]@'
<?xml version="1.0" encoding="ISO-8859-1"?>
 <bookstore>
     <book>
       <title lang="eng">Harry Potter</title>
       <price>29.99</price>
     </book>
     <book>
       <title lang="eng">Learning XML</title>
       <price>39.95</price>
     </book>
 </bookstore> 
'@

$xml.SelectNodes('//*') | Where {$_.ParentNode.Name -eq 'book'}

在回答有關訪問管道中另一個對象的問題時,將中間變量創建為可在以后引用的管道的一部分並不罕見:

Get-Process | Foreach {$processName = $_.Name; $_.Modules} | 
              Foreach {"$processName loaded $($_.ModuleName)"}

在這種情況下,我將System.Diagnostics.Process對象的名稱存儲起來,然后在管道中傳播完全不同的類型,即System.Diagnostic.ProcessModule。 然后我可以將隱藏的進程名稱與模塊的名稱組合以生成我想要的輸出。

上述方法有利於教學目的,但不是真正規范的PowerShell。 這是在PowerShell中執行此操作的更典型方法:

Get-Process | Select Name -Exp Modules | Foreach {"$($_.Name) loaded $($_.ModuleName)"}

在這種情況下,我們采用了Process的名稱並將其投影到每個ProcessModule對象中。 請注意,當您嘗試枚舉其模塊集合時,某些進程將生成錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM