【问题标题】:Powershell concatenation order with function variables and literals带有函数变量和文字的 Powershell 连接顺序
【发布时间】:2011-06-29 11:59:38
【问题描述】:

我不确定我是完全疯了还是错过了什么,但我正在尝试做一些非常简单的事情,即将函数中的变量负载分开并将它们写出来。

你说“容易”?我会这么想的。但这里是我尝试编写一个 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

四处搜索,我找到了几个替代方案,但似乎都没有产生正确的结果。我不确定整个“将所有变量集中在一起用空格分隔”到底是什么。

【问题讨论】:

    标签: string powershell concatenation


    【解决方案1】:

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

    而不是像这样调用函数

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

    你需要这样调用函数

    logEntry 0 "moomin" "plimsole"
    

    【讨论】:

    • 我在发这个但是你打败了我。随着这种变化,除了第三种方法之外,所有方法都给出了预期的结果。
    • 忘记了cmets不能回车,提早提交了。感谢那。我什至从来没有想过检查函数调用语法,因为这是我多年来一直使用的所有其他东西的方式。难怪在串联问题上什么都没有,因为实际上没有。
    【解决方案2】:

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

    logEntry 0 moomin plimsole
    

    【讨论】:

    • 来吧,你应该让我知道是否已经发布了答案。 :-)
    • 我确定我不是第一个,也不会是最后一个。这里还有一个地方,在那里寻找完全错误问题的答案的人会找到正确问题的答案。仍然是“一个人必须走多少条路?”对我来说听起来不错,即使是老鼠建议的。
    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    相关资源
    最近更新 更多