I am trying to develop a powershell script that will allow me to archive all files that are older than 2 years and copy over their parent directories to a new root folder. I would also like to delete the original file and any empty directories after the archiving has been completed.
I have the below function which should allow me to do the first part (moving the files and parent directories) being called from a test script at the moment and it is failing with the error:
Copy-Item : Cannot evaluate parameter 'Destination' because its argument is specified as a script block and there is no input. A script block cannot be evaluated without input. At C:\Users\cfisher\Documents\WindowsPowerShell\Modules\ShareMigration\ShareMigration.psm1:99 char:43 + Copy-Item -Force -Destination { + ~ + CategoryInfo : MetadataError: (:) [Copy-Item], ParameterBindingException + FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.CopyItemCommand
Here is the function:
Function ArchiveFiles { [CmdletBinding()]
Param (
[Parameter(Mandatory=$True)][string]$SourceDirectory,
[Parameter(Mandatory=$True)][string]$DestinationDirectory,
[Parameter(Mandatory=$True)][ValidateSet('AddMinutes','AddHours','AddDays','AddMonths','AddYears')][string]$TimeUnit,
[Parameter(Mandatory=$True)][int]$TimeLength
)
Begin {
Write-Host "Archiving files..." -ForegroundColor Yellow -BackgroundColor DarkGreen
}
Process {
$Now = Get-Date
$LastWrite = $Now.$TimeUnit(-$TimeLength)
$Items = Get-ChildItem -Path $SourceDirectory -Recurse | where { $_.LastWriteTime -lt "$LastWrite" }
ForEach($Item in $Items) {
Copy-Item -Force -Destination {
If ($_.PSIsContainer) {
If (!(Test-Path -Path $_.Parent.FullName)) {
New-Item -Force -ItemType Directory -Path
(
Join-Path $DestinationDirectory $_.Parent.FullName.Substring($SourceDirectory.length)
)
}
Else {
Join-Path $DestinationDirectory $_.Parent.FullName.Substring($SourceDirectory.length)
}
}
Else {
Join-Path $DestinationDirectory $_.FullName.Substring($SourceDirectory.length)
}
}
}
}
End {
Write-Host "Archiving has finished." -ForegroundColor Yellow -BackgroundColor DarkGreen
}
}
I thought that passing the results of Join-Path as input to the -Destination parameter would do the trick, but it does not seem to be playing along. Do I need to create new items for each path or something? Kind of new to powershell so sorry if this looks sloppy. I appreciate any constructive criticism and solutions.
Thanks!
… -Destination $(. { scrip_block_body_here })should work (note(). { }Dot sourcing operator and$( )Subexpression operator. SeeGet-Help 'about_Operators'. However, a dot sourced scriptblock must be a valid code snippet (and Iˇm not sure about yours one).