2

one-script.ps1 looks like this:

. $PSScriptRoot\another-script.ps1 

Param (
    [Parameter(Mandatory = $True)]
    [MyEnum]$enum
)


write-host "hi"

MyEnum is defined in another-script.ps1:

Add-Type -TypeDefinition @"
    public enum MyEnum {
        a, b, c, d
  }
"@

Running one-script.ps1 -enum badValue prints the validation exception as expected, but doesn't stop and prints "hi" as well. The reason I assume is that the Param block can't be preceded by the import statement.

However if I move the import statement below the Param block, the script fails because MyEnum type is undefined.

So how can I use MyEnum class while also having the validation check failure stop script from executing?

One solution is to add MyEnum in user profile, but it's not a good general solution to this problem. Any suggestions are appreciated.

5
  • If you have dependencies on your powershell scripts, you should consider to create Powershell Modules Commented Aug 11, 2015 at 7:44
  • Tried that. Having import-module before Param block has same effect as dot sourcing - it breaks validation. Commented Aug 11, 2015 at 8:02
  • You still using a script, not a module. Commented Aug 11, 2015 at 8:05
  • if I'm not wrong Param must be the first command in your script to work correctly Commented Aug 11, 2015 at 8:07
  • @ jisaak I don't understand what you mean. Can you describe how to solve my problem? Commented Aug 11, 2015 at 13:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.