4

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

1 Answer 1

8

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.