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

JMa*_*sch 13 powershell

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

考虑:


$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的凹槽!这可能是一些奇怪的语法规则,但我想了解规则.谁能帮我吗?

Sta*_*ing 19

实际上你在这里看到的是弄清楚一个变量何时停止而下一个变量开始的麻烦.它试图寻找$ 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
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • 也可以,但支架解决方案更清洁.$ fileName ="$($ baseName)_ $($ count)$($ Ext)"; $文件名 (2认同)

小智 7

你也可以使用"$ baseName`_ $ count $ Ext"