Home > Software engineering >  How do I set a default parameter value in powershell?
How do I set a default parameter value in powershell?

Time:04-04

I have the following function that converts a file to Base64. How do I make it so this function accepts a default value for the file path if one is not entered?

B64 -f $filePath

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

CodePudding user response:

How about:

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

When setting a default value on a parameter, you do not set it mandatory so the caller can call the function without adding that parameter.

By adding alias Path and/or FullName PLUS allowing the parameter to be set using ValueFromPipelineByPropertyName, you also allow the caller piping objects that have a Path of FullName property.

I also strongly advise you to use a better parameter name. As it is now (just the f), it confuses with the -f Format operator

Finally, if your function always expects a string, it wouldn't harm to define it as such using [string]$File = ...

As mklement0 commented if you want to use ValueFromPipelineByPropertyName, you must define the parameter variable $File as [string]

  • Related