Powershell连接顺序与函数变量和文字

时间:2011-02-17 23:48:53

标签: string powershell concatenation

我不确定我是否完全生气或遗漏了一些东西,但我正在尝试做一些非常简单的事情,它将函数中的变量加载分开并写出来。

你说“轻松”吗?我会这么想的。但是,这是我尝试编写一个powehell函数的一个小提取,以使我的代码的其余部分更容易在眼睛上。

$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")

输出:

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

在我周围搜索我发现了几种替代品,但似乎都没有产生正确的结果。我不确定整个“把所有变量放在一起的空间分开”的事情一目了然。

2 个答案:

答案 0 :(得分:3)

您正在错误地调用该函数。你将0,mommin和plimsole放入第一个变量,而第二个和第三个变量则没有。因此,你得到的输出。

而不是像这样调用函数

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

你需要像这样调用这个函数

logEntry 0 "moomin" "plimsole"

答案 1 :(得分:1)

经典的PowerShell误解。您调用函数就像调用cmdlet一样 - 空格分隔的参数而不是逗号分隔,例如:

logEntry 0 moomin plimsole