【问题标题】:PowerShell - Concatenating two strings with underscore inbetween not working?PowerShell - 连接两个带有下划线的字符串不起作用?
【发布时间】:2021-02-11 19:12:05
【问题描述】:

我正在尝试将时间戳附加到文件名,然后将该文件移动到另一个目录中。 这是一个代码示例:

$sourceFiles= Get-ChildItem $sourcePath\* -Include *.csv

ForEach($sourceFile in $sourceFiles)
{
    $fileNameWithoutExtension = $sourceFile.BaseName
    $timestamp = $(Get-Date -f yyyy-MM-dd_HH-mm_ss)
    $processedFile = Join-Path -Path $processedPath -ChildPath "$fileNameWithoutExtension_$timestamp.csv"   
    Move-Item -Path $sourceFile -Destination $processedFile
}

当我执行此操作时,"$fileNameWithoutExtension_$timestamp.csv" 似乎完全忽略了$fileNameWithoutExtension 变量的内容,并且仅将时间戳包含在文件名中。我也已经对此进行了调试并检查了$fileNameWithoutExtension 变量的内容,它确实包含正确的文件名,但没有扩展名。为什么会这样?如何正确创建文件名?

【问题讨论】:

    标签: string powershell concatenation concat string-concatenation


    【解决方案1】:

    这是因为下划线是变量名中的有效字符(看here),所以PowerShell 基本上连接$fileNameWithoutExtension_ + $timestamp + .csv。第一个变量(名称包括下划线)不存在,因此被解释为 null / 空。

    尝试以下解决方案之一(当然,还有更多):

    # curly-bracket-notation for variables
    "${fileNameWithoutExtension}_${timestamp}.csv"
    
    # sub-expression operator
    "$($fileNameWithoutExtension)_$($timestamp).csv"
    
    # escape character
    "$fileNameWithoutExtension`_$timestamp.csv"
    
    # format operator
    "{0}_{1}.csv" -f $fileNameWithoutExtension, $timestamp
    
    # string concetenation
    ($fileNameWithoutExtension + "_" + $timestamp + ".csv")
    

    【讨论】:

    • 感谢您的及时答复!我尝试了您的第一个解决方案,但它似乎有一个错误,因为它在文件名中包含括号。但是,第二个效果很好!
    • @Chris 我有点太快了,有一些拼写错误,但现在应该都已经修复了。我还添加了更多选项
    猜你喜欢
    • 2014-11-02
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多