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

I a*_*oby 4 powershell function default-parameters

我有以下将文件转换为 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 ''
        }
    }
Run Code Online (Sandbox Code Playgroud)

The*_*heo 7

怎么样:

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

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

通过添加别名Path和/或FullNamePLUS允许使用设置参数ValueFromPipelineByPropertyName,您还允许调用者管道对象具有PathofFullName属性。

我还强烈建议您使用更好的参数名称。就像现在一样(只是f),它与-f 格式运算符混淆了

最后,如果你的函数总是需要一个string,那么使用它来定义它并没有什么坏处[string]$File = ...

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