I am trying to build a function that detects duplicates. To try and figure out how to add parameters which take no input I Googled up this post:
http://powershell.com/cs/blogs/tips/archive/2009/06/26/using-switch-parameters.aspxSo, to use this in my own function, I added these definitions (snippet shown purely for demo purposes):
function Find-Duplicates
{
param(
[string]$filePath,
[switch]$recurse
)
# Test filePath for proper syntax
if(!$filePath.EndsWith("\")
{
$filePath = $filePath + "\"
}
# Create command for invoking search. This can be dynamically added to before invocation to avoid a bunch of if/then and switch conditions in the code.
$command = Get-ChildItem -Path $filePath
# Add Date recurse switch
if($recurse)
{
$command = $command + " -recurse"
}
# Run actual search
Invoke-Command $command
}When I call this function, I can simply call the function without the parameter:Find-Duplicates -Path C:In this case, the if will see $recurse as $false and not append the extra switch to the $command string we are building.To run this switch I simply add the
-recurse switch I define in my param list:Find-Duplicates -Path C:\ -recurseThe fact that the switch is present sets $recurse = $true within the script so the $command variable then becomes:Get-ChildItem -Path $path -RecurseIn effect the [switch] param allows for turning things on by merely adding the parameter to the call.
02.43
rian


0 komentar:
Posting Komentar