2016-06-15 145 views
1

將文件夾複製到其他位置後出現問題,我需要重命名目錄中的文件夾以從最後刪除「.deploy」,但我在下面得到以下錯誤消息。我搜索了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

您應該使用-Directory交換機上的Get-ChildItem cmdlet來只得到目錄。然後使用Rename-Item cmdlet重命名文件夾。我用的是-replace功能用一個簡單的regex以獲得新的文件夾名稱:

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

你甚至不必使用Foreach-Object小命令(Thanks to AnsgarWiechers):

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

沒用使用'的foreach Object'。 'Rename-Item'可以從管道中讀取,所以你可以直接給它提供'Get-ChildItem'的輸出。 –

+0

@AnsgarWiechers但你將如何訪問舊名稱來替換'.deploy'? –

+3

'... | Rename-Item -NewName {$ _。Name -replace'\ .deploy $'}'(注意花括號)。 –