【问题标题】:PowerShell equavalent code for C#C# 的 PowerShell 等效代码
【发布时间】:2012-05-15 23:13:44
【问题描述】:

我是 PowerShell 的新手,并且一直在努力将 C# 以下代码转换为 Powershell。

var vmDoc = XDocument.Load(vmStream);
var vmElement = vmDoc.Descendants(ns + "entry")
        .Descendants(ns + "content");
var vmId = vmElement.Descendants().Descendants(nsData + "VirtualMachineID").FirstOrDefault();

我尝试了下面的代码,但没有成功

$vmElement = vmDoc.Descendants(ns + "entry")
    $_.Descendants($ns + "content")
$vmId = $vmElement.Descendants().Descendants($nsData + "VirtualMachineID").FirstOrDefault()

希望有人可以帮助我!

提前致谢!

拉玛尼

【问题讨论】:

    标签: powershell


    【解决方案1】:

    看来您只是误解了 C# 中的换行符。换行没有任何意义,为了便于阅读,长行通常会延续到另一行。您在第 3 行错误地使用了 powershell“此管道”变量 $_

    $vmElement = vmDoc.Descendants(ns + "entry").Descendants($ns + "content")
    $vmId = $vmElement.Descendants().Descendants($nsData + "VirtualMachineID").FirstOrDefault()
    

    编辑:查看了documentation for the Descendants method,不清楚您的原始 C# 代码是否也可以工作。该方法返回一个IEnumerable<XElement>,它不会公开Descendants() 方法。

    我建议您在尝试转换为 Powershell 之前专注于获得有效的 C# 代码。

    这可能会对您有所帮助:Is there an easier way of using extension methods in Powershell v2
    还有这个:http://dougfinke.com/blog/index.php/2007/08/07/using-xmllinq-in-powershell/

    【讨论】:

    • 感谢 Jamiec 的快速响应!但我遇到了不同的错误 ..PS C:\Work\Scripts> $vmElement = $vmDoc.Descendants($ns + "entry").Descendants($ns + "content") 方法调用失败,因为 [System.Xml. Linq.XContainer+d__a] 不包含名为“Descendants”的方法。在 line:1 char:59 + $vmElement = $vmDoc.Descendants($ns + "entry").Descendants
    • 如果您可以在 C# 中提供问题的short, self contained, correct example,我很乐意帮助您调试 powershell。
    • 感谢 James 再次快速回复我。我在执行代码时遇到的问题是由 PowerShell 中不可用的扩展方法引起的。我想知道如何将 (.NET) 扩展导入 Powershell。我想在这里提供我的代码,但是由于空间限制,我不能这样做。
    猜你喜欢
    • 2014-03-21
    • 2015-03-26
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2015-10-05
    • 2012-11-23
    相关资源
    最近更新 更多