ValidateSet with variable

Welcome Forums General PowerShell Q&A ValidateSet with variable

Viewing 2 reply threads
  • Author
    Posts
    • #187591
      Participant
      Topics: 16
      Replies: 11
      Points: 64
      Rank: Member

      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
      Participant
      Topics: 2
      Replies: 136
      Points: 714
      Helping Hand
      Rank: Major Contributor
    • #187627
      Participant
      Topics: 9
      Replies: 1277
      Points: 1,051
      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
  • You must be logged in to reply to this topic.