我正在从xml文件中收集信息并进行处理.我的查询是自由的,以确保我得到我想要的所有可能的元素.因此,最终可能会在结果列表中显示重复元素(称为$components).我运行结果Sort-Object然后Get-Unique找到所有唯一对象.据我所知,应该留下每个独特对象中的一个Get-Unique.但它消除了一些已经很独特的对象(原始列表中没有重复的对象).
这是一个简化的例子.只需将其粘贴到PowerShell中或保存到ps1文件并运行(输出如下所示):
$xmlDoc = [xml]@'
<root>
<component Id='component1'>
<regkey Id='regkey1'/>
</component>
<component Id='component2'>
<file Id='file1' />
</component>
</root>
'@
$files = $xmlDoc.SelectNodes("//file[@Id='file1']")
$regkeys = $xmlDoc.SelectNodes("//regkey[@Id='regkey1']")
$components = $xmlDoc.SelectNodes("//component[@Id='component1'] | //component[@Id='component2']")
$components += $regkeys | Select-Object -ExpandProperty 'ParentNode'
$components | Sort-Object -Property 'Id'
Write-Host
$components | Sort-Object -Property 'Id' | Get-Unique
Run Code Online (Sandbox Code Playgroud)
如果您粘贴到PowerShell中,请在最后一行之后按Enter键.
输出是这样的:
PS C:\> $xmlDoc = [xml]@'
>> <root>
>> <component Id='component1'>
>> <regkey Id='regkey1'/>
>> </component>
>> <component Id='component2'>
>> <file …Run Code Online (Sandbox Code Playgroud) 我来到了我的PoweShell-fu的边缘.有人可以向我解释为什么这两个函数在管理数组数组时会有不同的行为吗?所有不同的是我是使用$_还是[parameter(ValueFromPipeline=$true)] $input获取管道输入.我希望那些人在这种情况下行事相同.
$pairs = ('a', 'b'), ('c', 'd')
function dollarUnderscoreFunction
{
Process
{
Write-Host "`$_[0] = $($_[0])"
Write-Host "`$_[1] = $($_[1])"
}
}
function pipedParameterFunction([parameter(ValueFromPipeline=$true)] $input)
{
Process
{
Write-Host "`$input[0] = $($input[0])"
Write-Host "`$input[1] = $($input[1])"
}
}
Write-Host "`$pairs:"
$pairs | foreach { Write-Host $_ }
Write-Host "`nRunning dollarUnderscoreFunction`n"
$pairs | dollarUnderscoreFunction
Write-Host "`nRunning pipedParameterFunction`n"
$pairs | pipedParameterFunction
Run Code Online (Sandbox Code Playgroud)
PowerShell v3中的输出:
$pairs:
a b
c d
Running dollarUnderscoreFunction
$_[0] = a
$_[1] = b
$_[0] …Run Code Online (Sandbox Code Playgroud) 通常,有没有一种方便的方法来确定PowerShell脚本/函数的哪些行返回值("未捕获")?我希望有一种方法可以在调试时查询要返回的值的当前状态.我可以在每一行后检查它,看看哪些行添加到它.
我有一些脚本在工作,有些行将我的返回值转换为Object [].我通常将这些线管道输出Out-Null来修复这种情况.我只想要返回一个对象(我在函数末尾选择的对象).
有些行是Cmdlet调用,有些是对其他函数的调用,有些是.NET对象的函数调用.
有谁知道using从 C# 文件中删除未使用语句的自动方法,但保留开发人员指定的某些语句?