Reputation: 361
I've got this function, that move a directory to inside another directory, but always gives me the access denied error.
Any idea what am i doing wrong?
Get-ChildItem C:\Scripts\MetadataExport -Directory | ForEach-Object {
# this will look for a 4-12 digit number in the directory name
If ($_.Name -match '(?:\b|\D)(\d{4,12})(?:\b|\D)') {
$destPath = Join-Path $_.Parent.Fullname $Matches[1]
If (-not (Test-Path -LiteralPath $destPath)) {
New-Item $destPath -ItemType Directory
}
Move-Item -LiteralPath $_.Fullname -Destination $destPath -Force
}
}
the error:
Move-Item : Access to the path 'C:\Scripts\MetadataExport\kwakwala-rosenblum-0172' is denied.
At C:\Users\User\Documents\ScripsPS1\MetadataExport.ps1:170 char:9
Move-Item -LiteralPath $_.Fullname -Destination $destPath -Fo ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : WriteError: (C:\Scripts\Meta...-rosenblum-0172:DirectoryInfo) [Move-Item], IOException
+ FullyQualifiedErrorId : MoveDirectoryItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand
So, the goal is to move every folder that part of the name matches with another folder with numeric name.
Ex:
The 'kwakwala-rosenblum-0172' folder needs to move to inside '0172' folder. Just move if the Literal-Path is the same as folder's name.
Upvotes: 0
Views: 2170
Reputation: 23613
I am not sure what you are trying to do but you effectively try to move a folder to a folder with the same name:
$Null = New-Item -Path .\0172 -ItemType Directory -Force
$Null = New-Item -Path .\kwakwala-rosenblum-0172 -ItemType Directory -Force
Get-ChildItem -Directory | Foreach-Object {
if ($_.Name -Match '(?:\b|\D)(\d{4,12})(?:\b|\D)') {
$destPath = Join-Path $_.Parent.Fullname $Matches[1]
Write-Host $_.Fullname '-->' $destPath
}
}
C:\..\0172 --> C:\..\0172
C:\..\kwakwala-rosenblum-0172 --> C:\..\0172
Which is the same as doing this:
Move-Item -LiteralPath .\0172 -Destination .\0172 -force
Move-Item: The process cannot access the file because it is being used by another process.
Meaning that this would likely "resolve" the issue:
if ($_.Fullname -ne $destPath) {
Move-Item -LiteralPath $_.Fullname -Destination $destPath -Force
}
But, I am not sure what your expectation is.
You might want to explain (in the question) how you expect the subfolders to be (re)named.
Upvotes: 1