ValidateSet with variable

Welcome Forums General PowerShell Q&A ValidateSet with variable

Viewing 2 reply threads
  • Author
    Posts
    • #187591
      Participant
      Topics: 17
      Replies: 15
      Points: 102
      Rank: Participant

      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
      }

    • #187606
      Moderator
      Topics: 3
      Replies: 218
      Points: 1,187
      Helping Hand
      Rank: Community Hero
    • #187627
      Participant
      Topics: 12
      Replies: 1618
      Points: 2,543
      Helping Hand
      Rank: Community Hero

      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
      
Viewing 2 reply threads
  • The topic ‘ValidateSet with variable’ is closed to new replies.