如何在PowerShell中设置默认参数值?

4
我有以下的函数,可以将文件转换为Base64。 如果用户没有输入文件路径,如何使该函数接受默认值呢?

B64 -f $filePath


提示:请勿修改HTML标签。
function B64{
    
    param (
    
    [Parameter (Mandatory = $True, ValueFromPipeline = $True)]
    [Alias("file")]
    $f

    )

    
    $File = "\converted.txt"
    $FilePath = ([Environment]::GetFolderPath("Desktop")+$File)

    $Content = Get-Content -Path $f 
    $converted = [convert]::ToBase64String([System.Text.encoding]::Unicode.GetBytes($Content))
    $numChar = $converted.length
    $incriment = 275

    $pre = "STRING powershell -enc "
    $string = "STRING "

    function splitLines{
        While ($converted)
        { 
        $x,$converted = ([char[]]$converted).where({$_},'Split',$incriment)
        $x -join ''
        }
    }
1个回答

7

怎么样:

[Parameter (Mandatory = $False, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Alias("Path", "FullName")]
[string]$File = Join-Path -Path ([Environment]::GetFolderPath("Desktop")) -ChildPath 'converted.txt'

当在参数上设置默认值时,不要将它设置为强制性的,这样调用者可以在不添加该参数的情况下调用函数。

通过添加别名 Path 和/或 FullName,并允许使用 ValueFromPipelineByPropertyName 设置参数,你还允许调用者对具有 PathFullName 属性的对象进行管道处理。

我还强烈建议你使用更好的参数名称。现在的名称(只是 f)容易与 格式运算符 -f 搞混。

最后,如果你的函数总是期望一个字符串,那么使用 [string]$File = ... 进行定义也无妨。

mklement0所评论的,如果你想使用 ValueFromPipelineByPropertyName,你必须将参数变量 $File 定义为 [string]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接