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

How do I set a default parameter value in powershell?

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

B64 -f $文件路径

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 ''
        }
    }

怎么样:

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

在为参数设置默认值时,您不必将其设置为强制性的,因此调用者可以在不添加该参数的情况下调用该函数。

通过添加别名 Path and/or FullName 加上允许使用 ValueFromPipelineByPropertyName 设置参数,您还允许调用者管道 objectsPathFullName 属性。

我也强烈建议您使用更好的参数名称。就像现在一样(只有 f),它与 -f Format operator

混淆了

最后,如果您的函数总是需要一个 字符串 ,那么使用 [string]$File = ...

来定义它也无妨

如果要使用ValueFromPipelineByPropertyName,则必须定义参数变量$File为[string]