ai didi

PowerShell:如何将对象通过管道传输到接受输入 "ByPropertyName"的参数?

转载 作者:行者123 更新时间:2023-12-04 18:43:18 24 4
gpt4 key购买 nike

这是一个示例 PowerShell 脚本(它不起作用),它说明了我想要做什么:

$BuildRoot = '_Provided from script parameter_'
$Files = 'a.dll', 'b.dll', 'c.dll'
$BuiltFiles = $Files | Join-Path $BuildRoot

我有一个文件名列表和一个目录名,我想将它们连接在一起,很简单。问题是这不起作用,因为 Join-Path参数 -ChildPath接受来自管道ByPropertyName的输入,所以报如下错误:

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.



我可以通过将行更改为以下内容来“修复”它:
$BuiltFiles = $Files | Select @{ Name = "ChildPath"; Expression = {$_}} | join-path $BuildRoot 

基本上, select操作是将对象转换为属性值。这是有效的,但它引入了很多句法噪音来完成一些看似微不足道的事情。如果这是唯一的方法,那就这样吧,但我想让这个脚本在 future 可以为人们维护,乍一看有点难以理解。

有没有更干净的方法来完成我在这里要做的事情?

最佳答案

您可以像这样更轻松地完成此操作:

$Files = 'a.dll', 'b.dll', 'c.dll'
$Files | Join-Path $BuildRoot -ChildPath {$_}

注意:你不想放 {}围绕文件。这会在 PowerShell 中创建一个脚本块,它本质上是一个匿名函数。此外,当参数受管道限制时,您可以使用提供脚本块( {} )的技巧,其中 $_在该脚本块中定义为当前管道对象。

关于PowerShell:如何将对象通过管道传输到接受输入 "ByPropertyName"的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19984216/

24 4 0
文章推荐: markdown - Markdown 中的签名行
文章推荐: LINQ to XML 中的 F# 和显式转换
文章推荐: apache-camel - Apache Camel 并发消费者与线程
文章推荐: graphviz - 有没有办法在 Graphviz 上绘制 B 树?
行者123
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com