? 添加到字符串Powershell
我正在尝试使用powershell重命名文件? 添加到字符串Powershell,powershell,powershell-ise,Powershell,Powershell Ise,我正在尝试使用powershell重命名文件 $oldPath="c:\users\guest\desktop\old.txt" $newName="c:\users\guest\desktop\new.txt" Rename-Item -Path $oldPath -NewName $newName -Force; 我得到以下错误 Rename-Item : Cannot find drive. A drive with the name 'C' does not exist. 查看
$oldPath="c:\users\guest\desktop\old.txt"
$newName="c:\users\guest\desktop\new.txt"
Rename-Item -Path $oldPath -NewName $newName -Force;
我得到以下错误
Rename-Item : Cannot find drive. A drive with the name 'C' does not exist.
查看Notepad++中的代码后,我意识到在这两条路径前面都添加了一个“?”,这在powershell ise中是不可见的
在记事本+++“?c:\users\guest\desktop\old.txt”中可见的路径
我无法使用$oldPath进行修剪。TrimStart(“?”)
同时我会尝试清除特殊字符的路径(因为问号在ISE中不可见,它可能不是问号,而是一些特殊字符)。你可以这样做:
$oldPath = $oldPath -replace '[^\w\\:."]', ''
$newName = $newName -replace '[^\w\\:."]', ''
function Remove-InvalidCharacters ([string]$fileName) {
$invalid = [IO.Path]::GetInvalidPathChars() -join ''
$pattern = "[{0}]" -f [RegEx]::Escape($invalid)
return ($fileName -replace $pattern, '')
}
$oldPath = Remove-InvalidCharacters "c:\users\guest\desktop\old.txt"
$newName = Remove-InvalidCharacters "c:\users\guest\desktop\new.txt"
if (Test-Path $oldPath -PathType Leaf) {
Rename-Item -Path $oldPath -NewName $newName -Force
}
else {
Write-Warning "Path '$oldPath' not found"
}
当然,您可以始终使用一个小函数来删除代码中的无效文件名字符,如下所示:
$oldPath = $oldPath -replace '[^\w\\:."]', ''
$newName = $newName -replace '[^\w\\:."]', ''
function Remove-InvalidCharacters ([string]$fileName) {
$invalid = [IO.Path]::GetInvalidPathChars() -join ''
$pattern = "[{0}]" -f [RegEx]::Escape($invalid)
return ($fileName -replace $pattern, '')
}
$oldPath = Remove-InvalidCharacters "c:\users\guest\desktop\old.txt"
$newName = Remove-InvalidCharacters "c:\users\guest\desktop\new.txt"
if (Test-Path $oldPath -PathType Leaf) {
Rename-Item -Path $oldPath -NewName $newName -Force
}
else {
Write-Warning "Path '$oldPath' not found"
}
重命名Item-Path($oldPath-replace“\?”)
等。我发现不可见字符的ASCII值是8234,我可以这样修剪$oldPath.TrimStart([char]8234)。但我只是想知道是什么导致了这个问题。您是如何在Powershell中输入代码的?你可能是从什么地方复制/粘贴的吗?我在这里看到了[这是用于从左到右嵌入的unicode字符。这是一个编码问题。因为反斜杠被认为是无效字符,仅供参考。你应该跳过该数组的最后两个字符。你是对的。我现在已经更新了答案。应该是GetInvalidPathChars而不是GetInvalidFileNameChars