2014-09-23 61 views
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 
    } 
} 

回答

0
[Int]$Quantity(Mandatory=$true) 
+0

謝謝RAF,但'Quantity'只有'Mandatory'在'ParameterSetName = B'時,選擇「OlderThan」。所以它並不總是強制性的。也許有一種方法可以告訴我使用'ParameterSetName = B'的腳本? – DarkLite1 2014-09-23 10:47:02

+0

如果您正在從CSV中讀取數據,則傳入的每個PSObject都將具有數量屬性,即使它爲空。因此,它將始終查看參數集B,但您將傳入一個空值。嘗試使用-debug調用您的函數以獲取更多信息。 – 2014-09-23 14:08:15