Get-ChildItem recurse as a parameter in PowerShell

送分小仙女□ 提交于 2019-12-01 00:55:04

问题


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 | 

...

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

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.


回答1:


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 | ...



回答2:


The PowerShell V1 way to approach this is to use the method described in the other answers (-recurse:$recurse), but in V2 there is a new mechanism called splatting that can make it easier to pass the arguments from one function to another.

Splatting will allow you to pass a dictionary or list of arguments to a PowerShell function. Here's a quick example.

$Parameters = @{
    Path=$home
    Recurse=$true
}
Get-ChildItem @Parameters

Inside of each function or script you can use $psBoundParameters to get the currently bound parameters. By adding or removing items to $psBoundParameters, it's easy to take your current function and call a cmdlet with some the functions' arguments.

I hope this helps.




回答3:


I asked a similar question before... My accepted answer was basically that in v1 of PowerShell, just passing the named parameter through like:

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



回答4:


Here's a good list of the types of parameters you can use:

param(
    [string] $optionalparam1, #an optional parameter with no default value
    [string] $optionalparam2 = "default", #an optional parameter with a default value
    [string] $requiredparam = $(throw ""requiredparam required."), #throw exception if no value provided
    [string] $user = $(Read-Host -prompt "User"), #prompt user for value if none provided
    [switch] $switchparam; #an optional "switch parameter" (ie, a flag)
    )

From here



来源:https://stackoverflow.com/questions/1862554/get-childitem-recurse-as-a-parameter-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!