复制后重命名文件夹

Rename Folders After Copy

将文件夹复制到其他位置后出现问题,我需要重命名目录中的文件夹以从末尾删除“.deploy”,但出现以下错误。我用 Google 搜索了 PowerShell 管理员权限,但似乎找不到适合我的场景的 'catch-all'。

Get-Content : Access to the path 'C:\OldUserBackup\a.deploy' is denied.
At C:\PSScripts\DesktopSwap\TestMergeDir.ps1:28 char:14
+             (Get-Content $file.PSPath) |
+              ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\OldUserBackup\a.deploy:String) [Get-Content], UnauthorizedAccessException
    + FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand

这是我的:

$UserName = [Environment]::UserName
$CurrUser = [Environment]::UserName + '.deploy'
$OldUserDir = 'C:\OldUserBackup'
$CurrDate = Get-Date -format G

$PathExist = Test-Path $OldUserDir

if ($PathExist -eq $true) {
    #Copy Desktop, Downloads, Favorites, Documents, Music, Pictures, Videos
    Copy-Item -Path $OldUserDir -Destination C:\Users$UserName\Desktop\CopyTest -Recurse -Force

    $configFiles = Get-ChildItem $OldUserDir *.deploy -rec
    foreach ($file in $configFiles) {
        (Get-Content $file.PSPath) |
            Foreach-Object { $_ -replace ".deploy", "" } |
            Set-Content $file.PSPath
    }
} 

您应该在 Get-ChildItem cmdlet to only get directories. Then use the Rename-Item cmdlet 上使用 -Directory 开关来重命名文件夹。我使用 -replace 函数和一个简单的 regex 来获取新文件夹名称:

$deployFolders = Get-ChildItem $OldUserDir *.deploy -rec -Directory
$deployFolders | Foreach { 
    $_ | Rename-Item -NewName ($_.Name -replace ('\.deploy$') )
}

您甚至不必使用 Foreach-Object cmdlet ():

Get-ChildItem $OldUserDir *.deploy -rec -Directory | 
    Rename-Item -NewName { $_.Name -replace ('\.deploy$') }