【问题标题】:How to make this PowerShell function return a plain string, but not return an array of string?如何使此 PowerShell 函数返回纯字符串,但不返回字符串数组?
【发布时间】:2014-07-11 04:30:45
【问题描述】:

尽管$logDir 变量包含值"C:\Users\DEVELO~1\AppData\Local\Temp\logs"(从文本文件中获得),但这段代码的行为并不符合我的预期。它返回一个字符串数组,而不是单个字符串。

$LogFileName = "NoIP-update.log"
$ConfigSection = "NoIp"

function Log-Message ($MSG) {
    $script:Logger += "$(get-date -format u) $MSG`n"
    Write-Output $MSG
}

function Get-LogFileName ($config) {
    $Local:logDir = $config["Section"]["LOGDIR"]
    if ($Local:logDir -ne "") {
      Log-Message "Testing for directory '$Local:logDir'"
      if(!(Test-Path -Path $Local:logDir )){
          New-Item -ItemType directory -Path $Local:logDir
          Log-Message "Created directory '$Local:logDir'"
      }
      return "$Local:logDir\$LogFileName"
    }
    return $LogFileName
}

我可能遗漏了一些非常基本的东西,因为我希望函数返回 1 个字符串,而不是字符串数组并记录一两行。

但是,它不记录,并且:如果$Local:logDir 存在,则该函数返回一个由2 个字符串组成的数组,否则它返回一个由4 个字符串组成的数组。

  • 为什么?
  • 如何让它返回 1 个字符串并仍然记录?

我认为这与使用流水线隐喻的思考与我在过程和面向对象编程语言方面的背景有关。非常感谢您的帮助(:

2 字符串数组:

{Testing for directory 'C:\Users\DEVELO~1\AppData\Local\Temp\logs', C:\Users\DEVELO~1\AppData\Local\Temp\logs\NoIP-update.log}

4 字符串数组:

{Testing for directory 'C:\Users\DEVELO~1\AppData\Local\Temp\logs', C:\Users\Developer\AppData\Local\Temp\logs, Created directory 'C:\Users\DEVELO~1\AppData\Local\Temp\logs', C:\Users\DEVELO~1\AppData\Local\Temp\logs\NoIP-update.log}

注意事项:

  • 我在 PowerGUI 内运行,但在 PowerShell 控制台中运行结果相同。
  • $PSVersionTable.PSVersion 返回4.0

【问题讨论】:

    标签: arrays string powershell windows-8.1 powershell-4.0


    【解决方案1】:

    我的问题在于Log-Message,特别是Write-Output这一行。

    当您在函数中使用Write-Output 时,它被视为从函数返回值的一种方式(即它可以与Return 互换使用)。所以发生的事情是您的日志消息被包含在Return 流中。

    如果您只想在显示屏上显示日志记录信息,请改用Write-Host。这将向主机显示信息,但不会包含在您的Return 流中。

    因此,解决方法是将您的 Log-Message 函数更改为:

    function Log-Message ($MSG) {
        $script:Logger += "$(get-date -format u) $MSG`n"
        Write-Host $MSG
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多