Powershell文件重命名日期/时间


1

我使用了上一篇文章中的脚本并对其进行了稍微修改:

Get-ChildItem "c:\test\*.txt" | ForEach-Object {          
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')-$(Get-Date -Format "ddMMyyyy").txt"
}

然而:

当前重命名的文件:test-ddmmyy.txt
必需格式:testddmmyy.txt

Answers:


1

这应该工作。

Get-ChildItem "c:\test\*.txt" | ForEach-Object {          
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "ddMMyyyy").txt"

你的破折号从前一刻开始$(Get-Date。请记住,当使用双引号作为参数传递内容时,任何不是变量或不在括号内并且在其前面的内容$都将被视为字符串字符。

在下面的脚本中:

$test='test';"$test-$(Get-Date -F 'ddMMyyyy')"

$test将被扩展为其值'test'-将保持独立,因为它既不是变量也不是表达式的一部分,并且Get-Date -F 'ddMMyyyy'将被处理并返回其输出,因为它被设置为带有$(... 的表达式)。这将导致:

test-24112013

摆脱破折号,......

$test='test';"$test-$(Get-Date -F 'ddMMyyyy')"

....输出...

test24112013
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.