代码之家  ›  专栏  ›  技术社区  ›  JMarsch

使用PowerShell进行奇怪的字符串扩展

  •  12
  • JMarsch  · 技术社区  · 15 年前

    我正在使用字符串扩展功能来构建文件名,我不太明白发生了什么。

    考虑:

    
    $baseName = "base"
    [int]$count = 1
    $ext = ".ext"
    
    $fileName = "$baseName$count$Ext"
    #filename evaluates to "base1.ext" -- expected
    
    #now the weird part -- watch for the underscore:
    $fileName = "$baseName_$count$Ext"
    #filename evaluates to "1.ext" -- the basename got dropped, what gives?
    
    

    只需添加下划线似乎就完全脱离了PowerShell的最佳状态!这可能是一些奇怪的语法规则,但我想理解这个规则。有人能帮我吗?

    3 回复  |  直到 9 年前
        1
  •  18
  •   Zian Choy    9 年前

    实际上,您在这里看到的是一个问题,即如何确定一个变量何时停止,下一个变量何时开始。它试图寻找$basename。

    修复方法是将变量括在大括号中:

    $baseName = "base" 
    [int]$count = 1 
    $ext = ".ext" 
    
    $fileName = "$baseName$count$Ext" 
    #filename evaluates to "base1.ext" -- expected 
    
    #now the wierd part -- watch for the underscore: 
    $fileName = "$baseName_$count$Ext" 
    #filename evaluates to "1.ext" -- the basename got dropped, what gives?
    
    $fileName = "${baseName}_${count}${Ext}" 
    # now it works
    $fileName
    

    希望这有帮助

        2
  •  7
  •   hoge    15 年前

    您也可以使用 “$basename`$count$ext”

        3
  •  3
  •   Anon.    15 年前

    下划线是标识符中的合法字符。因此,它正在查找一个名为 $baseName_ .这是不存在的。