Repository navigation
Closed
Labels
Needs-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or more
Description
Prerequisites
- Write a descriptive title.
- Make sure you are able to repro it on the latest released version
- Search the existing issues.
- Refer to the FAQ.
- Refer to Differences between Windows PowerShell 5.1 and PowerShell.
Steps to reproduce
Create two files in a directory.
test.ps1
using module './testvalidate.psm1'
param
(
[Parameter(Mandatory)]
[ValidateSet([TestValidate])]
[string]$foo
)
testvalidate.psm1
class TestValidate : System.Management.Automation.IValidateSetValuesGenerator
{
[String[]] GetValidValues()
{
$values = @()
$values += 'bar'
$values += 'baz'
return $values
}
}
Expected behavior
cmdlet test.ps1 at command pipeline position 1
Supply values for the following parameters:
foo:Actual behavior
InvalidOperation: E:\Software development\Royalty Calculator\trunk.powershell\test.ps1:6
Line |
6 | [ValidateSet([TestValidate])]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Unable to find type [TestValidate].Error details
Exception :
Type : System.Management.Automation.RuntimeException
ErrorRecord :
Exception :
Type : System.Management.Automation.ParentContainsErrorRecordException
Message : Unable to find type [TestValidate].
HResult : -2146233087
TargetObject : [ValidateSet([TestValidate])]
CategoryInfo : InvalidOperation: ([ValidateSet([TestValidate])]:AttributeAst) [], ParentContainsErrorRecordException
FullyQualifiedErrorId : TypeNotFound
InvocationInfo :
ScriptLineNumber : 6
OffsetInLine : 5
HistoryId : -1
ScriptName : E:\Software development\Royalty Calculator\trunk.powershell\test.ps1
Line : [ValidateSet([TestValidate])]
PositionMessage : At E:\Software development\Royalty Calculator\trunk.powershell\test.ps1:6 char:5
+ [ValidateSet([TestValidate])]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot : E:\Software development\Royalty Calculator\trunk.powershell
PSCommandPath : E:\Software development\Royalty Calculator\trunk.powershell\test.ps1
CommandOrigin : Internal
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
TargetSite :
Name : NewValidateSetAttribute
DeclaringType : System.Management.Automation.Language.Compiler, System.Management.Automation, Version=7.3.4.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35
MemberType : Method
Module : System.Management.Automation.dll
Message : Unable to find type [TestValidate].
Data : System.Collections.ListDictionaryInternal
Source : System.Management.Automation
HResult : -2146233087
StackTrace :
at System.Management.Automation.Language.Compiler.NewValidateSetAttribute(AttributeAst ast)
at System.Management.Automation.Language.Compiler.GetAttribute(AttributeAst attributeAst)
at System.Management.Automation.Language.Compiler.GetRuntimeDefinedParameter(ParameterAst parameterAst, Boolean& customParameterSet, Boolean& usesCmdletBinding)
at System.Management.Automation.Language.Compiler.GetParameterMetaData(ReadOnlyCollection`1 parameters, Boolean automaticPositions, Boolean& usesCmdletBinding)
at System.Management.Automation.CompiledScriptBlockData.InitializeMetadata()
at System.Management.Automation.CompiledScriptBlockData.Compile(Boolean optimized)
at System.Management.Automation.PSScriptCmdlet..ctor(ScriptBlock scriptBlock, Boolean useNewScope, Boolean fromScriptFile, ExecutionContext context)
at System.Management.Automation.CommandProcessor.Init(IScriptCommandInfo scriptCommandInfo)
at System.Management.Automation.CommandDiscovery.GetScriptAsCmdletProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext context, Boolean useNewScope, Boolean fromScriptFile, SessionStateInternal sessionState)
at System.Management.Automation.CommandDiscovery.CreateCommandProcessorForScript(ExternalScriptInfo scriptInfo, ExecutionContext context, Boolean useNewScope, SessionStateInternal sessionState)
at System.Management.Automation.CommandDiscovery.CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, Boolean useLocalScope, SessionStateInternal sessionState)
at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(CommandInfo commandInfo, CommandOrigin commandOrigin, Nullable`1 useLocalScope, SessionStateInternal sessionState)
at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource)
at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext context)
at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject : [ValidateSet([TestValidate])]
CategoryInfo : InvalidOperation: ([ValidateSet([TestValidate])]:AttributeAst) [], RuntimeException
FullyQualifiedErrorId : TypeNotFound
InvocationInfo :
ScriptLineNumber : 6
OffsetInLine : 5
HistoryId : -1
ScriptName : E:\Software development\Royalty Calculator\trunk.powershell\test.ps1
Line : [ValidateSet([TestValidate])]
PositionMessage : At E:\Software development\Royalty Calculator\trunk.powershell\test.ps1:6 char:5
+ [ValidateSet([TestValidate])]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot : E:\Software development\Royalty Calculator\trunk.powershell
PSCommandPath : E:\Software development\Royalty Calculator\trunk.powershell\test.ps1
CommandOrigin : Internal
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1Environment data
Name Value
---- -----
PSVersion 7.3.4
PSEdition Core
GitCommitId 7.3.4
OS Microsoft Windows 10.0.19045
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0Visuals
No response
Metadata
Metadata
Assignees
Labels
Needs-TriageThe issue is new and needs to be triaged by a work group.Resolution-No ActivityIssue has had no activity for 6 months or more
Activity
MarcelVersteeg commentedon May 19, 2023
rhubarb-geek-nz That could indeed be the issue, because when I give the command
using module ./testvalidate.psm1on the powershell prompt and then run my script, it runs correctly (with the expected results).It would be nice that the
using modulecan also be handled before theparamdeclaration, preventing the need to actually install the used module. I actually do not want to have the module with the class definition installed, but still use the class definition for the[ValidateSet]attribute.I guess this will need to be a feature request then.
MarcelVersteeg commentedon May 19, 2023
rhubarb-geek-nz But then I will loose the tab-completion on that parameter, right?
MarcelVersteeg commentedon May 19, 2023
rhubarb-geek-nz No, I cannot use a static set, as the validation set is actually dynamic, based on configuration files that might change. I do not want to copy the values from those files into the script due to maintenance. I just used the simple example to show what is going wrong.
mklement0 commentedon May 19, 2023
Your symptom is a variation of a long-standing, fundamental problem that appears to be a distinct bug:
Any types referenced in a
param(...)block (orclassdefinition) must already have been loaded into the session at parse time,using modulenormally does provide parse-time access toclasses andenums defined in the referenced module, but this seemingly only works in the body of a script, and unexpectedly not inside aparam(...)block.As an aside: Note that neither
using modulenorusing assemblycan currently provide parse-time access to types from binary assemblies. The - long-standing - plain is to fix this, to allowclassdefinitions to use .NET types loaded viausing moduleandusing assemblystatements, but this hasn't happened yet, presumably because the implementation is non-trivial; see the following for a technical discussion:There's also a meta issue tracking all
class-related problems:MarcelVersteeg commentedon May 19, 2023
They might change from run to run
That would be possible, but that is also something to forget as a user. So for me, and also from a user perspective, this is really a no-go.
Of course that is possible, but that would mean that all shortcuts to PowerShell need to be updated on the machines that the users are using (even including Linux machines). Not a very nice scenario.
mklement0 commentedon May 19, 2023
There is a workaround, but it is somewhat cumbersome:
It relies on the fact that referencing types in script blocks used in parameter attributes happens at runtime, so the imported type is then already available:
The unfortunate side effect of using
ArgumentCompleterwith a script block (rather than with anIArgumentCompleter-implementing class) is that if what the user typed doesn't match any of the valid values, the default file-name completion behavior kicks in; see:microsoft-github-policy-service commentedon Nov 17, 2023
This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.
microsoft-github-policy-service commentedon Nov 24, 2023
This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.
mklement0 commentedon Jan 25, 2024
totkeks commentedon Mar 25, 2024
After trying my luck in the PowerShell discord (https://discord.com/channels/180528040881815552/1221837959922192455) I found this issue through the long list of class issues.
I see the issue is closed, but I don't understand why, because the issue itself still exists.
I have the same issue with my GitManagement module that uses
IValidateSetValuesGeneratorto validate against the actual git repositories checked out on my PC, which of course is a dynamic set and not a static set.It also fails when using the
using modulemethod to import the classes into the.ps1files that use them in theValidateSet.With the help of the PowerShell discord, I also tried to switch to dot sourcing the classes as
.ps1(instead of.psm1) files in the root module, but this also fails, because of #4114I will try out your workaround next.
Edit: Workaround works. 👍