Powershell 脚本中哪些行返回输出?
一般来说,是否有一种方便的方法来确定 PowerShell 脚本/函数的哪些行正在返回值(“未捕获”)?我希望有一种方法可以在调试时查询要返回值的当前状态。我可以在每一行之后检查它,看看添加了哪些行。
我有一些脚本正在工作,有些行正在将我的返回值转换为 Object[]。我通常将这些行通过管道传输到 Out-Null 来解决这种情况。我只想返回一个对象(我在函数末尾选择的对象)。
有些行是 Cmdlet 调用,有些是对其他函数的调用,有些是对 .NET 对象的函数调用。
In general, is there a convenient way to figure out which lines of a PowerShell script/function are returning values (are "uncaptured")? I was hoping there was a way to query the current state of the to-be-returned value while debugging. I can check it after each line to see which lines add to it.
I have some scripts at work and some lines are turning my return value into an Object[]. I usually pipe such lines to Out-Null to fix the situation. I only want one object returned (the one I pick at the end of the function).
Some of the lines are Cmdlet calls, some are calls to other functions, and some are function calls on .NET objects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想您可以使用 Set-PsDebug -trace 1 来查看哪一行返回它们。
示例:
考虑下面的脚本:
执行
Set-PsDebug -trace 1
后,跟踪将如下所示:显然,您可以看到输出来自何处。但如果输出被捕获,你就不会得到这个。
另外,如果您不关心返回的其他对象,而只想获取使用
return
语句返回的最后一个对象,您始终可以执行类似(func )[-1]
或func |选择 -last 1
(如评论中指出的)以获取最后一个。I suppose you can use
Set-PsDebug -trace 1
to see which line is returning them.Example:
Consider the script below:
After doing
Set-PsDebug -trace 1
, the trace would be something like below:Clearly, you can see where the output is coming from. But if the output is captured, you wouldn't get this.
Also, if you don't care about the other objects that are being returned and only want to get the last one that you returned with the
return
statement, you can always do something like(func)[-1]
orfunc | select -last 1
( as pointed out in the comment) to get the last one.为了完成可能的答案,我想添加 2 个注释:
首先,如果您使用
func | select -last 1
,如果返回数组本身,则必须将返回的对象包装到数组中。为什么?看一个失败的示例:其次,如果您不确切知道哪些命令返回输出,您可以像这样将它们全部
Out-Null
:只需尝试将 ArrayList 代码放在脚本块之外,您就会发现看看它做了什么。使用
.
符号在脚本块内运行它意味着脚本块在当前范围内执行。Out-Null
只是吃掉Add
方法的输出。To complete the possible answer, I'd like to add 2 notes:
First, if you use
func | select -last 1
, you have to wrap returned object to array, if you return array itself. Why? Look at a failing sample:Second, if you don't know exactly what commands return output, you can
Out-Null
them all like this:Just try to put the ArrayList code outside the scriptblock and you will see what it does. Running it inside scriptblock with
.
notation means, that the scriptblock is executed in current scope.Out-Null
just eats the output fromAdd
methods.