Passing a set of characters to a function as a string without quotes

This topic contains 2 replies, has 2 voices, and was last updated by  Adam Bertram 4 years, 1 month ago.

  • Author
  • #15812

    Adam Bertram

    I'm trying to create a dead simple function in my profile that I can simply type "log something I just did". The log will be the function name and the "I just did" will be some note. I realize I can easily just wrap the "I just did" in quotes and make this work but I want something that I can extremely quick just jot down a note. I know myself. If I have to worry about putting quotes around the "I Just did" string, I'll mentally resent it.

    Anyone know of a way I can just type this line: log this is a note

    ..and pass "this is a note" as a string or another datatype that I can convert to a string that I can turn around and add to a text file? How would I tell Powershell to treat "this is a note" as a single parameter instead of 4 separate parameters?

  • #15813

    Dave Wyatt

    You can't pass a string with spaces without quoting it, but you could define a parameter with the ValueFromRemainingArguments attribute set. You'd wind up with an array of strings passed to the function, which it could then join into a single string. Something like this:

    function log
        param (
            [Parameter(ValueFromRemainingArguments = $true)]
        $string = $Text -join ' '
        Write-Host "Logging: $string"
    log Something I just did.
  • #15814

    Adam Bertram

    ValueFromRemainingArguments is exactly what I was looking for. Thanks!

You must be logged in to reply to this topic.