String PowerShell-在两个字符串之间连接下划线不起作用?
我试图在文件名上附加一个时间戳,然后将该文件移动到另一个目录中。 下面是一个代码示例:String PowerShell-在两个字符串之间连接下划线不起作用?,string,powershell,concatenation,concat,string-concatenation,String,Powershell,Concatenation,Concat,String Concatenation,我试图在文件名上附加一个时间戳,然后将该文件移动到另一个目录中。 下面是一个代码示例: $sourceFiles= Get-ChildItem $sourcePath\* -Include *.csv ForEach($sourceFile in $sourceFiles) { $fileNameWithoutExtension = $sourceFile.BaseName $timestamp = $(Get-Date -f yyyy-MM-dd_HH-mm_ss)
$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
变量的内容,它确实包含了正确的文件名,但没有扩展名。这是为什么?我如何才能正确创建文件名?这是因为下划线是变量名(look)中的一个有效字符,因此PowerShell基本上会将$fileNameWithoutExtension.
+$timestamp
+.csv
连接起来。第一个变量(名称包括下划线)不存在,因此它被解释为null/空
尝试以下解决方案之一(当然,还有更多):
#变量的花括号表示法
“${fileNameWithoutExtension}{timestamp}.csv”
#子表达式运算符
“$($fileNameWithoutExtension)$($timestamp).csv”
#转义字符
“$fileNameWithoutExtension`\u$timestamp.csv”
#格式运算符
“{0}{1}.csv”-f$fileNameWithoutExtension,$timestamp
#弦凝聚
($fileNameWithoutExtension+“”+$timestamp+”.csv)
感谢您的及时回复!我尝试了您的第一个解决方案,但其中似乎有一个错误,因为它在文件名中包含了括号。然而,第二个很好用@克里斯我有点太快了,有一些拼写错误,但他们现在都应该被修复。我还添加了一些其他选项