Get-ChildItem 作为 PowerShell 中的参数递归 [英] Get-ChildItem recurse as a parameter in PowerShell

查看:75
本文介绍了Get-ChildItem 作为 PowerShell 中的参数递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个函数,可以在 cmdlet 中切换递归能力 Get-ChildItem.

I am looking to create a function that could toggle the ability to recurse in cmdlet Get-ChildItem.

举一个非常基本的例子:

As a very basic example:

...

param 
(   
    [string] $sourceDirectory = ".",
    [string] $fileTypeFilter = "*.log",
    [boolean] $recurse = $true
)

Get-ChildItem $sourceDirectory -recurse -filter $fileTypeFilter | 

...

如何有条件地将 -recurse 标志添加到 Get-ChildItem 而不必求助于某些 if/else 语句?

How does one conditionally add the -recurse flag to Get-ChildItem without having to resort to some if/else statement?

我想也许可以用 $recurseText 参数替换 Get-ChildItem 语句中的 -recurse(如果 $recurse 为真,则设置为-recurse"),但这似乎不起作用.

I thought perhaps one could just substitute the -recurse in the Get-ChildItem statement with a $recurseText parameter (set to "-recurse" if $recurse were true), but that does not seem to work.

推荐答案

这里有几件事.首先,您不想使用 [boolean] 作为递归参数的类型.这要求您在脚本上为 Recurse 参数传递一个参数,例如-递归 $true.你想要的是一个 [switch] 参数,如下所示.此外,当您将开关值转发到 Get-ChildItem 上的 -Recurse 参数时,请使用 : ,如下所示:

A couple of things here. First, you don't want to use [boolean] for the type of the recurse parameter. That requires that you pass an argument for the Recurse parameter on your script e.g. -Recurse $true. What you want is a [switch] parameter as shown below. Also, when you forward the switch value to the -Recurse parameter on Get-ChildItem use a : as shown below:

param (
    [string] $sourceDirectory = ".",
    [string] $fileTypeFilter = "*.log",
    [switch] $recurse
)

get-childitem $sourceDirectory -recurse:$recurse -filter $fileTypeFilter | ...

这篇关于Get-ChildItem 作为 PowerShell 中的参数递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆