【问题标题】:Why is my string variable not concatenating in my Powershell function?为什么我的字符串变量没有在我的 Powershell 函数中连接?
【发布时间】:2019-09-09 15:00:59
【问题描述】:

我正在向 Write-EventLog 编写一个函数,其中的信息会根据参数而变化。这些参数之一是消息,但它不会显示在实际的事件日志中。只有硬编码的字符串部分。

我已经尝试将它分配给一个变量并输出它以确保它存在并且它表明即使变量类型是字符串它也不会在函数中连接。

$testmsg1 = "The script successfully completed an operation"

Function Log-This($level, $message){

    If ($level -eq "Information"){
        $testmsg1
        $msg = "INFO: $message" 
        $msg
        Write-EventLog -LogName Application `
            -EventId 1099 `
            -EntryType Information `
            -Message $msg `
            -Source "Windows Error Reporting"
        }
... 
}
$testmsg1.GetType()

Log-This "Information", $testmsg1

这会产生:

IsPublic IsSerial Name                                     BaseType                                                                                                                        
-------- -------- ----                                     --------                                                                                                                        
True     True     String                                   System.Object                                                                                                                   
The script successfully completed an operation
INFO: 

我要的是字符串“INFO:脚本成功完成操作”。我做错了什么没有字符串连接?

【问题讨论】:

  • 不要在函数调用中使用方括号。写Log-This "Information" $testmsg1
  • @Theo 感谢您指出这一点。它不会改变结果或行为,但我会做出这些改变。
  • @datagreenhorn 请相应地更新您的问题!
  • @tituszban 你好,提图斯。我的问题是为什么当我将传递给该函数的参数连接到消息变量时无法识别它们。
  • 函数调用中也不要使用逗号。

标签: function powershell event-log


【解决方案1】:

在调用函数时,您需要单独识别它的参数。

例如

Log-This -level "Information" -message $testmsg1

感谢@js2010 指出这一点。

【讨论】:

    【解决方案2】:

    也不要在函数调用中使用逗号。

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2014-11-23
      • 1970-01-01
      • 2012-12-07
      • 2016-01-20
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多