PowerShell自定义函数中字符串变量无法拼接问题咨询
问题根源:函数调用的参数传递方式错误
你遇到的问题核心是调用函数时用了逗号分隔参数,这在PowerShell里是错误的用法——逗号会把多个值打包成一个数组传给第一个参数,导致第二个参数$message根本没接收到值,自然拼接不出完整字符串。
具体分析
看你调用函数的代码:
Log-This "Information", $testmsg1
这里的逗号是PowerShell的数组构造符,所以$level参数实际收到的是一个包含两个元素的数组:["Information", "The script successfully completed an operation"],而$message因为没被传入任何值,默认是$null。这就导致$msg = "INFO: $message"拼接后变成了INFO: 。
你可以在函数里加一行$level.GetType()验证,会看到输出的类型是Object[]而不是预期的String。
修复方案
把调用时的逗号改成空格,PowerShell里函数的多个参数是用空格分隔传递的:
Log-This "Information" $testmsg1
修改后的完整代码示例
$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" } # 其他level的逻辑... } $testmsg1.GetType() Log-This "Information" $testmsg1
预期输出
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object The script successfully completed an operation INFO: The script successfully completed an operation
内容的提问来源于stack exchange,提问作者level_0_apprentice
相关产品推荐
相关产品推荐

