复制后重命名文件夹

时间:2016-06-15 13:49:37

标签: powershell copy administrator access

我将文件夹复制到其他位置后遇到问题,我需要重命名目录中的文件夹以删除" .deploy"从最后,但我得到以下错误。我已经用Google搜索了PowerShell管理员权限,但似乎无法找到一个全面的'对于我的情景。

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
    }
} 

1 个答案:

答案 0 :(得分:1)

您应该使用Get-ChildItem cmdlet上的-Directory开关来获取目录。然后使用Rename-Item cmdlet重命名文件夹。我使用-replace函数和一个简单的regex来获取新文件夹名称:

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

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

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