Passing string with spaces as an argument to a PowerShell function

Tag: powershell Author: ldtong04 Date: 2011-11-16

I have a really simple PowerShell function that I use to make notes to myself:

New-Alias Note CreateNote    
function CreateNote ( [string]$note )
{
    $message = "`n" + $note
    Add-Content C:\notes.txt $message 
    Write-Host "Saved note."
}

This works great as long as I call it with a quoted string:

PS > Note "This is a note to myself."

I'd really like to be able to omit the quotes, similar to how Write-Host works:

PS > Write-Host This is a note to myself.
This is a note to myself.

It seems doable if I handle the arguments as an array and concatenate them before appending them to the text file. Is there a better way to do this?

Best Answer

You could use $args to accomplish this:

function CreateNote
{
    $message = "`n" + $args
    Add-Content D:\notes.txt $message 
    Write-Host "Saved note."
}

CreateNote this is a test

comments:

Nice--worked like a charm. Stack Overflow won't let me mark this as the answer for five more minutes, though. :)