ValidateSet with variable

How can I make the “ValidateSet” to work with $cred from the BEGIN section ?

I know that [ValidateSet(‘domain1\user2’, ‘domain1\user1’,"$cred")] will not work .

function Get-folderssize {
[CmdletBinding()]

Param(

[Parameter(Mandatory = $True)]
[Alias(‘CN’, ‘MachineName’, ‘Name’)]
[string[]]$ComputerName,

[Parameter(Mandatory = $True)]
[ValidateSet(‘domain1\user2’, ‘domain1\user1’)]
[string]$Credencial,

[Parameter(Mandatory = $True)]
[string]$Path

)

BEGIN {

$encrypted = “01000000”
$user = “domain1\user1”
$password = ConvertTo-SecureString -string $encrypted
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user, $password
}

Hi Arik,

You can use ValidateScript instead of ValidateSet.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6#validatescript-validation-attribute

Please refer to this link.

Thank you.

It’s not a best practice to manage permissions with a function wrapper, the permissions should be managed on the endpoint where you accessing folder permissions. To provide an example, you would need to do a ValidateScript to parse out the username from the Credential object.

function Test-It {
    [CmdletBinding()]

    Param(

        [Parameter(Mandatory = $True)]
        [ValidateScript({
            if ('MyUserName','YourUserName' -contains $_.UserName) {
                $True
            } else {
                Throw [System.UnauthorizedAccessException] ("The user {0} is not authorized." -f $_.UserName)
            }
        })]
        [PSCredential]$Credential
    )

    begin{}
    process{'Processing user {0}' -f $Credential.UserName}
    end{}
}

Test-It -Credential $creds