繁体   English   中英

PowerShell不要等待参数

[英]PowerShell Don't wait for parameter

我有一个功能可以将x天之前的文件从一个目录移动到另一个目录。 这对于两个可用参数集都可以完美地工作。 当我手动运行该函数而忘记了Quantity ,PowerShell会提示我填写它。这应该是这样的。

但是,当我运行处理这些参数的脚本而忘记了输入CSV文件中的“ Quantity时,它不会为缺少的“ 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>]

参数:

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 '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
    }
}
[Int]$Quantity(Mandatory=$true)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM