Bodestone
Bodestone

Reputation: 54

Powershell concatenation order with function variables and literals

I'm not sure if I am completely mad or missing something but I am trying to do something very simple which is pipe separate a load of variables in a function and write them out.

"Easy" you say? I would have thought so. But here is a wee extract of my attempts to write a powehell function to make the rest of my code a little easier on the eye.

$logtoFile=$false
function logEntry($entryType, $section, $message)
{

    #The way I assumed woudl work
    $logString1 = $(get-Date -format "yyyy-MM-dd hh:mm:ss") + "|" + $entryType + "|" + $section + "|" + $message
    #Another way which should also work
    $logString2 = "$(get-Date -format "yyyy-MM-dd hh:mm:ss")|$entryType|$section|$message"
    #Proof that it is not the pipes causing issues
    $logString3 = "$(get-Date -format "yyyy-MM-dd hh:mm:ss"),$entryType,$section,$message"
    #another method I found. Not sure what the issue is there
    $logString4 = $(get-Date -format "yyyy-MM-dd hh:mm:ss"), $entryType, $section, $message -join "|"
    $WhatIwant = $(get-Date -format "yyyy-MM-dd hh:mm:ss") + "|0|moonin|plimsole"

    if($script:logtoFile)
    {
        Add-Content $logFile $logString
    }
    else
    {
        write-host $logString1
        write-host $logString2
        write-host $logString3
        write-host $logString4
        write-host $whatIwant
    }
}
logEntry(0,"moomin","plimsole")

Output:

2011-02-17 11:22:59|System.Object[]||
2011-02-17 11:22:59|0 moomin plimsole||
2011-02-17 11:22:59,0 moomin plimsole,,
2011-02-17 11:22:59|0 moomin plimsole||
2011-02-17 11:22:59|0|moonin|plimsole

Searching around I found several alternatives, none of which seem to produce the right results. I'm not sure what the whole "lump all of the variables together space separated" thing as all about in the first place.

Upvotes: 2

Views: 190

Answers (2)

Keith Hill
Keith Hill

Reputation: 201692

Classic PowerShell misunderstanding. You call functions just like you call cmdlets - space separated arguments instead of comma separated e.g.:

logEntry 0 moomin plimsole

Upvotes: 1

user463535
user463535

Reputation:

You're calling the function incorrectly. You are putting 0, mommin, and plimsole into the first variable, and nothing for the second and third variables. Hence, the output you are getting.

Instead of calling the function like this

logEntry(0,"moomin","plimsole")

You need to call the function like this

logEntry 0 "moomin" "plimsole"

Upvotes: 3

Related Questions