【发布时间】:2020-09-09 14:30:42
【问题描述】:
我基本上是在尝试 trim() 任何在名称末尾有前导或尾随空格的文件名。这是我目前得到的代码
$foldersToCheck = "$env:userprofile\documents", "$env:userprofile\pictures", "$env:userprofile\desktop"
foreach ($folder in $foldersToCheck) {
get-childitem -path $folder -recurse | foreach-object {
if ($_.name.startswith(" ") -or $_.name.endswith(" ")) {
$newName = $_.name.trim()
rename-item -path $_ -newName $newname
}
}
}
如果我创建了一个测试文件 (c:\users\someusername\desktop\test.txt),那么我会收到此错误
rename-item : Cannot rename because item at ' test.txt' does not exist.
At line:6 char:13
+ rename-item -path $_ -newName $newname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
所以,它看起来好像找到了需要重命名的文件,但又说它不存在。
【问题讨论】:
标签: powershell trim