毫無美感,但應該工作:
$myfilepath = 'C:\temp\abc2017 06.txt'
$file = Get-Item $myFilePath -Force
$basename = $file.basename
$basename -match '^(?<name>\D+)(?<year>\d{4})\s(?<month>\d{2})'
$dateString = "{0}/{1}/01" -f $matches.year, $matches.month
$Datetime = $dateString | Get-Date
$Datetime = $Datetime.AddMonths(-1)
$newBasename = "{0} {1} {2}{3}" -f $matches.name, $Datetime.ToString('MM'), $Datetime.ToString('yyyy'), $file.Extension
更新:您的正則表達式不匹配,我改變了它一下。
Update2:將其寫入文件,然後根據需要調用它。
param(
[string]$myFilePath
)
$file = Get-Item $myFilePath -Force
$basename = $file.basename
$null = $basename -match '^(?<name>\D+)(?<year>\d{4})\s(?<month>\d{2})'
$dateString = "{0}/{1}/01" -f $matches.year, $matches.month
$Datetime = $dateString | Get-Date
$Datetime = $Datetime.AddMonths(-1)
$newFilename = "{0} {1} {2}{3}" -f $matches.name, $Datetime.ToString('MM'), $Datetime.ToString('yyyy'), $file.Extension
return $newFilename
例如爲:ConvertFilename.ps1 -myFilePath「C:\嗒嗒」
我會做幾行,可能無需替換。只需''匹配'basename',利用'$ matches'並做你的計算。之後,再次使用'-f'運算符構建基本名稱字符串。 – restless1987
這不是我所需要的,但可以放置示例 –