首页 > 解决方案 > 我需要在我的powershell脚本中添加对参数的依赖条件什么是最好的方法?

问题描述

param (
[Parameter(Mandatory=$true, HelpMessage="action")]
[ValidateSet('deploy','remove')]
[string]$action = "list",
[Parameter( Mandatory=$false, HelpMessage="zip File")]
[ValidateScript({
        if(-Not ($_ | Test-Path) ){
           throw "File or folder does not exist"
        }
        if(-Not ($_ | Test-Path -PathType Leaf) ){
            throw "The Path argument must be a file. Folder paths are not allowed."
        }
        if($_ -notmatch "(\.zip)"){
            throw "The file specified in the path argument must be a zipFile"
       }
        return $true 
    })]
[System.IO.FileInfo]$zipFile
)

这些是我的脚本中的参数,我想在此处添加一个条件,例如 zipFile 参数只有在部署操作时才应该是强制性的,我们可以添加这可能是使用动态参数吗?像这样的东西会起作用吗?

    param(
    [Parameter(Mandatory=$true, HelpMessage="action")]
[ValidateSet('deploy','remove')]
[string]$action = "list",
[Parameter( Mandatory=$false, HelpMessage="zip File")]
[ValidateScript({
        if(-Not ($_ | Test-Path) ){
           throw "File or folder does not exist"
        }
        if(-Not ($_ | Test-Path -PathType Leaf) ){
            throw "The Path argument must be a file. Folder paths are not allowed."
        }
        if($_ -notmatch "(\.zip)"){
            throw "The file specified in the path argument must be a zipFile"
       }
        return $true 
    })]
[System.IO.FileInfo]$zipFile
    )
    DynamicParam {
         if ($action -eq "deploy"){
         $zipFile.Mandatory = $true
           }
         }
    process {
    #Here comes script
    }

标签: powershell

解决方案


推荐阅读