【发布时间】:2018-03-14 23:17:03
【问题描述】:
我正在尝试开发一个 powershell 脚本,该脚本将允许我存档所有超过 2 年的文件并将其父目录复制到新的根文件夹。我还想在归档完成后删除原始文件和所有空目录。
我有下面的函数,它应该允许我做第一部分(移动文件和父目录),目前正在从测试脚本调用,但它失败并出现错误:
Copy-Item:无法评估参数“Destination”,因为它的参数被指定为脚本块并且没有输入。没有输入就无法评估脚本块。 在 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
函数如下:
函数存档文件 { [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
}
}
我认为将 Join-Path 的结果作为输入传递给 -Destination 参数可以解决问题,但它似乎并没有发挥作用。我是否需要为每条路径或其他东西创建新项目?如果这看起来很草率,那么对 powershell 有点陌生。我感谢任何建设性的批评和解决方案。
谢谢!
【问题讨论】:
-
我从来没有用脚本块复制项目。为什么你不在 join-path 命令前面使用复制项?
-
这是个好主意。让我试一试。
-
为什么不直接使用 Robocopy?
-
… -Destination $(. { scrip_block_body_here })应该可以工作(注意(). { }点源运算符 和$( )子表达式运算符。请参阅Get-Help 'about_Operators'。但是,点源脚本块必须是有效的代码 sn-p(我不确定您的代码)。
标签: windows powershell scripting archive copy-item