【发布时间】:2018-11-15 13:24:28
【问题描述】:
我正在尝试进行简单的批量文件重命名,以从文件名的开头删除非标准字符(例如“0123456789-_.”),然后在文件名中添加一个字符串。
例如'12 -_myfilename.doc' 会变成 '012345 - myfilename.doc'
...其中 012345 是我的学习编号。我尝试使用下面的脚本,但在单步执行执行 trimstart 行的脚本时不断收到以下错误...
"'Name' 是只读的"属性"
我猜这不是微调启动问题,而是我试图从中收集结果的方式。
任何帮助表示赞赏。
代码的相关部分看起来像...
$MyFileObject=0
if ($MyRecursiveFlag) {
Get-ChildItem $MyStudyPath -recurse | where {$_.extension -in ".xls",”.xlsx”,".xslt",".pdf",".doc",".docx",".xlsm",".xml",".htm",".ppt"}|
ForEach-Object{
#Check if start of the file is compliant
$mymatch = [Regex]::Match($_, '\d{5}\s-\s')
if ($mymatch.Success){
#Already renamed correctly so nothing else to do
Write-Host "Okay - no changes $($_.Name)" -ForegroundColor Green
} else {
#No, it's not compliant so let's remove any preceding numbers, spaces and dashes etc
$MyFileObject = $_
$MyFileObject.Name = $MyFileObject.Name.trimstart(" 0123456789-_.")
#...and rename the file
Rename-Item -LiteralPath $MyFileObject.FullName -NewName "$($MyStudyNumber + ' - ' + $MyFileObject.Name)"
Write-Host "Renamed to $($MyFileObject.Name)" -ForegroundColor Yellow
}
}
}
我在使用 Windows 7 PowerShell v3 和 5.1 时遇到了同样的问题
【问题讨论】:
标签: powershell trim readonly