0
我有一个功能可以将比x天早的文件从一个目录移动到另一个目录。这与两个可用的参数集完美无瑕地工作。当我手动运行该功能并忘记了Quantity
时,PowerShell正在提示我填写它。这是应该的。PowerShell不要等待参数
但是,当我运行脚本来解决这些参数,并且我忘记输入CSV文件中的Quantity
时,它不会为丢失的Quantity
丢失错误。如何在不提供时强制它发出错误?在我的脚本
Function Move-Files {
[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName='A')]
Param (
[parameter(Mandatory=$true,Position=0,ParameterSetName='A')]
[parameter(Mandatory=$true,Position=0,ParameterSetName='B')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path $_ -PathType Container})]
[String]$Source,
[parameter(Mandatory=$false,Position=1,ParameterSetName='A')]
[parameter(Mandatory=$false,Position=1,ParameterSetName='B')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path $_ -PathType Container})]
[String]$Destination = $Source,
[parameter(Mandatory=$false,ParameterSetName='A')]
[parameter(Mandatory=$false,ParameterSetName='B')]
[ValidateSet('Year','Year\Month','Year-Month')]
[String]$Structure = 'Year-Month',
[parameter(Mandatory=$true,ParameterSetName='B')]
[ValidateSet('Day','Month','Year')]
[String]$OlderThan,
[parameter(Mandatory=$true,ParameterSetName='B')]
[Int]$Quantity
)
线:所以它不会等待或提示我填写好...
语法:
Move-Files [-Source] <String> [[-Destination] <String>] [-Structure <String>] [-WhatIf ] [-Confirm ] [<CommonParameters>]
Move-Files [-Source] <String> [[-Destination] <String>] [-Structure <String>] -OlderThan <String> -Quantity <Int32> [-WhatIf ] [-Confirm ] [<CommonParameters>]
参数
Move-Files -Source 'S:\Test' -Destination 'S:\Target' -Structure Year\Month -OlderThan Day
这在foreach
循环使用像这样:
$File | ForEach-Object {
$MoveParams = @{
Source = $_.Source
Destination = $_.Destination
Structure = $_.Structure
OlderThan = $_.OlderThan
Quantity = $_.Quantity
}
Try {
Move-Files @MoveParams
}
Catch {
"Error reported"
}
解决方法:
$MoveParams.Values | ForEach-Object {
if ($_ -eq $null) {
Write-Error "Incomplete parameters:`n $($MoveParams | Format-Table | Out-String)"
Return
}
}
谢谢RAF,但'Quantity'只有'Mandatory'在'ParameterSetName = B'时,选择“OlderThan”。所以它并不总是强制性的。也许有一种方法可以告诉我使用'ParameterSetName = B'的脚本? – DarkLite1 2014-09-23 10:47:02
如果您正在从CSV中读取数据,则传入的每个PSObject都将具有数量属性,即使它为空。因此,它将始终查看参数集B,但您将传入一个空值。尝试使用-debug调用您的函数以获取更多信息。 – 2014-09-23 14:08:15