简体   繁体   English

PowerShell 字符串格式在 function 中的不同行为

[英]PowerShell string format different behaviour within function

While using powershell I struggle to build up a filename from two variables.在使用 powershell 时,我很难从两个变量中建立一个文件名。 When I originally creaded the powershell script, it was working fine.当我最初创建 powershell 脚本时,它运行良好。 Now I have tried to move some repeatable steps into a function, but the string behaviour is different.现在我尝试将一些可重复的步骤移动到 function 中,但字符串行为不同。

MWE: MWE:

$topa = "ABC"
$topb = "XYZ"

function Test-Fun{
    param(
        $a, 
        $b
        )
    echo "$($a)H$($b).csv"
}

echo "$($topa)H$($topb).csv"

Test-Fun($topa, $topb)

The output on my system is我系统上的 output 是

ABCHXYZ.csv
ABC XYZH.csv

Originally, I wanted to use an underscore instead of H and thought that is causing issues, but its not.最初,我想使用下划线而不是 H 并认为这会导致问题,但事实并非如此。 What did I miss or rather what is the difference between string expansion within a function and outside of it?我错过了什么,或者更确切地说,function 内部和外部的字符串扩展有什么区别?

You are calling Test-Func wrong.您调用Test-Func是错误的。 The comma after $topa will create an array, so you basically pass []"ABC", "XYZ" as an array to $a . $topa之后的逗号将创建一个数组,因此您基本上将 []"ABC", "XYZ" 作为数组传递给$a In that case $b is empty!在这种情况下$b是空的!

You can easily fix this by removing the comma (also the parentheses are not necessary):您可以通过删除逗号轻松解决此问题(括号也不是必需的):

Test-Fun $topa $topb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM