Loop

This topic contains 9 replies, has 4 voices, and was last updated by Profile photo of Mark Prior Mark Prior 3 months, 2 weeks ago.

  • Author
    Posts
  • #51131
    Profile photo of Mark Prior
    Mark Prior
    Participant

    Hi all trying to muddle my way through sapien PS Studio

    have created a small script to find who has access to a mailbox that can be used by the Service desk guys, how do i loop this so that the program does not end when the $result string is closed?

    
    
    $formMailboxRights_Load= {
    	#TODO: Initialize Form Controls here
    	
    	Set-ExecutionPolicy -ExecutionPolicy Unrestricted
    }
    
    	$Mailbox_TextChanged = {
    		
    		
    	}
    	
    	$buttonOK_Click = {
    	#TODO: Place custom script here
    	
    		Set-ExecutionPolicy -ExecutionPolicy Unrestricted
    		$Username = "global\mark.prior"
    		$Password = ConvertTo-SecureString "xxxxxx" -AsPlainText -Force
    		$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
    		
    		$SESJA_EX = New-PSSession -Credential $cred -ConnectionUri http://eurxhub02/powershell -ConfigurationName microsoft.exchange
    		Import-PSSession $SESJA_EX
    		
    		$result = Get-Mailbox $Mailbox.Text | Get-MailboxPermission | where { $_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false } | Select-Object user, accessrights
    		$result | out-GridView
    		if ($result -eq $null)
    		{
    			[System.Windows.Forms.MessageBox]::Show("User Has No Delagates Assigned", "Information")
    			
    		}
    		
    		
    		Remove-PSSession $sesja_ex
    	}
    	
    	$labelDisplayName_Click = {
    		#TODO: Place custom script here
    		
    	}
    	
    	$buttonReset_Click = {
    		#TODO: Place custom script here
    		
    		$Mailbox.Clear()
    	}
    
    • This topic was modified 3 months, 3 weeks ago by Profile photo of Mark Prior Mark Prior.
  • #51172
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    One issue in the code is you are piping $result to Out-Gridview, even if it's null. Your code logic should look more like this:

    $result = Get-Mailbox $Mailbox.Text | 
              Get-MailboxPermission | 
              where { $_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false } | 
              Select-Object user, accessrights
    
    
    if ($result) {
        $result | Out-GridView	
    }
    else {
       [System.Windows.Forms.MessageBox]::Show("User Has No Delegates Assigned", "Information") 
    }
    
  • #51178
    Profile photo of Mark Prior
    Mark Prior
    Participant

    Thanks Rob, have used that snippet

  • #51184
    Profile photo of Trevor Freedland
    Trevor Freedland
    Participant

    You probably want to disable the $buttonOK button right after it is clicked to prevent users from accidentally initiating that code block multiple times before it completes.

    $buttonOK_Click = {
        $this.enabled = $false
        
        # code goes here
    
        $this.enabled = $true
    }
    

    What kind of input field are you using? Seems like it may be beneficial to allow the user to pass in a txt|csv file containing multiple mailboxes to check in a single session.

    Personally I like output results to a listbox, and give the user a save-to button. Once you add a listbox in your winForm, Sapien will automatically drop in the Load-Listbox helper function, making it a breeze to work with.

    Is the whole form application closing when you close the OGV/ message box? Typically the form doesn't close until you click the 'x' in the upper right corner.

    • This reply was modified 3 months, 3 weeks ago by Profile photo of Trevor Freedland Trevor Freedland. Reason: formatting
  • #51248
    Profile photo of Mark Prior
    Mark Prior
    Participant

    Hi Trevor

    thanks for the tip, this is literally my first attempt at PS Studio so all advice welcome 🙂

    Will add this snippet also, have found finding any training material a little scarce and originally tried to add the list box (Unsuccessfully), the multi user option likely would not be used by the first line guys, lots of little extras i would like to add such as catching the error if a user / Mailbox does not exist.

    yes everything closes after OGV,

    thanks

    • #51250
      Profile photo of Trevor Freedland
      Trevor Freedland
      Participant

      Hey Mark, happy to help 🙂

      I was unable to recreate the form closing on my side. I made a little form with an example of how to output to a listbox. It's just a basic form with a few buttons, one to clear the form, one to output to the listbox, and one to ogv.

      With Load-Listbox, that portion is as simple as:

      $buttonGO_Click = {
          $results = Get-Process
          Load-ListBox $listboxOutput "The results are:"
          Load-ListBox $listboxOutput $results.Name -Append
      }
      
      $buttonCLEAR_Click = { $listboxOutput.Items.Clear() }
      
      

      Here is the .psf and an export if you want to load it up in PS Studio.
      https://github.com/tfreedland/Listbox_Example

      When you are running the form and it closes with ogv, are you launching the form from the Play button in the IDE or from the packaged .exe? If the latter, perhaps try a different target platform, such as WinForms v3 x64.

      • This reply was modified 3 months, 3 weeks ago by Profile photo of Trevor Freedland Trevor Freedland. Reason: formatting
  • #51433
    Profile photo of Mark Prior
    Mark Prior
    Participant

    Still struggling im afraid, how do i get $result to display in the list box ?, once i can see a working solution with my own scenario im hoping everything will click into place 🙂

    $formMailboxRights_Load= {
    	#TODO: Initialize Form Controls here
    	
    	Set-ExecutionPolicy -ExecutionPolicy Unrestricted
    }
    
    	$Mailbox_TextChanged = {
    		
    		
    	}
    	
    	$buttonOK_Click = {
    	$this.enabled = $false
    	
    		Set-ExecutionPolicy -ExecutionPolicy Unrestricted
    	$Username = "global\mark.prior"
    	$Password = ConvertTo-SecureString "xxxxxxxx" -AsPlainText -Force
    	$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
    	
    	$SESJA_EX = New-PSSession -Credential $cred -ConnectionUri http://eurxhub02/powershell -ConfigurationName microsoft.exchange
    	Import-PSSession $SESJA_EX
    	
    	$result = Get-Mailbox $Mailbox.Text |
    	Get-MailboxPermission |
    	where { $_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false } |
    	Select-Object user, accessrights
    	
    	
    		Remove-PSSession $sesja_ex
    	
    	
    	$this.enabled = $true
    	
    	}
    	
    	$labelDisplayName_Click = {
    		#TODO: Place custom script here
    		
    	}
    	
    	$buttonReset_Click = { $Mailbox.Clear()
    		#TODO: Place custom script here
    	
    	
    	}
    
    
    
    
    #region Control Helper Functions
    function Load-ListBox 
    {
    
    	Param (
    		[ValidateNotNull()]
    		[Parameter(Mandatory=$true)]
    		[System.Windows.Forms.ListBox]$ListBox,
    		[ValidateNotNull()]
    		[Parameter(Mandatory=$true)]
    		$Items,
    	    [Parameter(Mandatory=$false)]
    		[string]$DisplayMember,
    		[switch]$Append
    	)
    	
    	if(-not $Append)
    	{
    		$listBox.Items.Clear()	
    	}
    	
    	if($Items -is [System.Windows.Forms.ListBox+ObjectCollection] -or $Items -is [System.Collections.ICollection])
    	{
    		$listBox.Items.AddRange($Items)
    	}
    	elseif ($Items -is [System.Collections.IEnumerable])
    	{
    		$listBox.BeginUpdate()
    		foreach($obj in $Items)
    		{
    			$listBox.Items.Add($obj)
    		}
    		$listBox.EndUpdate()
    	}
    	else
    	{
    		$listBox.Items.Add($Items)	
    	}
    
    	$listBox.DisplayMember = $DisplayMember	
    }
    #endregion
    
    $listBox_SelectedIndexChanged={
    	#TODO: Place custom script here
    	
    	
    }
    
    
    • This reply was modified 3 months, 2 weeks ago by Profile photo of Mark Prior Mark Prior.
  • #51453
    Profile photo of Mark Prior
    Mark Prior
    Participant

    managed to get it :), now just to format the data so its not out of line, also managed to stop the app from quitting – button behaviour there

  • #51467
    Profile photo of Dan Potter
    Dan Potter
    Participant

    fyi, there are a couple people on the sapien forums that will fix your psf's for you if you post there ;D

    as for help, there is a ton of information out there. Full instructions on every control are on MSDN, helps if you know a little vb or C. Right click a control in the designer gives you links to msdn or the sapien spotlight article.

    
    #------------------------------------------------------------------------
    # Source File Information (DO NOT MODIFY)
    # Source ID: fa888ff9-5c9a-4649-917b-63463c3e4944
    # Source File: C:\Users\\Documents\SAPIEN\Files\sapienexamples.psf
    #------------------------------------------------------------------------
    
    
    #----------------------------------------------
    #region Application Functions
    #----------------------------------------------
    
    #endregion Application Functions
    
    #----------------------------------------------
    # Generated Form Function
    #----------------------------------------------
    function Call-sapienexamples_psf {
    
    	#----------------------------------------------
    	#region Import the Assemblies
    	#----------------------------------------------
    	[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
    	[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
    	[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
    	[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
    	[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
    	#endregion Import Assemblies
    
    	#----------------------------------------------
    	#region Generated Form Objects
    	#----------------------------------------------
    	[System.Windows.Forms.Application]::EnableVisualStyles()
    	$form1 = New-Object 'System.Windows.Forms.Form'
    	$textbox1 = New-Object 'System.Windows.Forms.TextBox'
    	$button1 = New-Object 'System.Windows.Forms.Button'
    	$datagridview1 = New-Object 'System.Windows.Forms.DataGridView'
    	$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    	#endregion Generated Form Objects
    
    	#----------------------------------------------
    	# User Generated Script
    	#----------------------------------------------
    	
    	$form1_Load = {
    		
    		$creds = get-credential 
    		
    		$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $creds -Authentication Basic -AllowRedirection
    		
    		Import-PSSession $Session
    		
    	}
    	
    	#region Control Helper Functions
    	function Load-DataGridView
    	{
    		
    		Param (
    			[ValidateNotNull()]
    			[Parameter(Mandatory=$true)]
    			[System.Windows.Forms.DataGridView]$DataGridView,
    			[ValidateNotNull()]
    			[Parameter(Mandatory=$true)]
    			$Item,
    		    [Parameter(Mandatory=$false)]
    			[string]$DataMember,
    			[System.Windows.Forms.DataGridViewAutoSizeColumnMode]$AutoSizeColumns = 'None'
    		)
    		$DataGridView.SuspendLayout()
    		$DataGridView.DataMember = $DataMember
    		
    		if ($Item -is [System.Data.DataSet] -and $Item.Tables.Count -gt 0)
    		{
    			$DataGridView.DataSource = $Item.Tables[0]
    		}
    		elseif ($Item -is [System.ComponentModel.IListSource]`
    		-or $Item -is [System.ComponentModel.IBindingList] -or $Item -is [System.ComponentModel.IBindingListView] )
    		{
    			$DataGridView.DataSource = $Item
    		}
    		else
    		{
    			$array = New-Object System.Collections.ArrayList
    			
    			if ($Item -is [System.Collections.IList])
    			{
    				$array.AddRange($Item)
    			}
    			else
    			{
    				$array.Add($Item)
    			}
    			$DataGridView.DataSource = $array
    		}
    		
    		if ($AutoSizeColumns -ne 'None')
    		{
    			$DataGridView.AutoResizeColumns($AutoSizeColumns)
    		}
    		
    		$DataGridView.ResumeLayout()
    	}
    	
    	function ConvertTo-DataTable
    	{
    		
    		[OutputType([System.Data.DataTable])]
    		param(
    		[ValidateNotNull()]
    		$InputObject, 
    		[ValidateNotNull()]
    		[System.Data.DataTable]$Table,
    		[switch]$RetainColumns,
    		[switch]$FilterWMIProperties)
    		
    		if($null -eq $Table)
    		{
    			$Table = New-Object System.Data.DataTable
    		}
    		
    		if ($InputObject -is [System.Data.DataTable])
    		{
    			$Table = $InputObject
    		}
    		elseif ($InputObject -is [System.Data.DataSet] -and $InputObject.Tables.Count -gt 0)
    		{
    			$Table = $InputObject.Tables[0]
    		}
    		else
    		{
    			if (-not $RetainColumns -or $Table.Columns.Count -eq 0)
    			{
    				#Clear out the Table Contents
    				$Table.Clear()
    				
    				if ($null -eq $InputObject) { return } #Empty Data
    				
    				$object = $null
    				#find the first non null value
    				foreach ($item in $InputObject)
    				{
    					if ($null -ne $item)
    					{
    						$object = $item
    						break
    					}
    				}
    				
    				if ($null -eq $object) { return } #All null then empty
    				
    				#Get all the properties in order to create the columns
    				foreach ($prop in $object.PSObject.Get_Properties())
    				{
    					if (-not $FilterWMIProperties -or -not $prop.Name.StartsWith('__')) #filter out WMI properties
    					{
    						#Get the type from the Definition string
    						$type = $null
    						
    						if ($null -ne $prop.Value)
    						{
    							try { $type = $prop.Value.GetType() }
    							catch { }
    						}
    						
    						if ($null -ne $type) # -and [System.Type]::GetTypeCode($type) -ne 'Object')
    						{
    							[void]$table.Columns.Add($prop.Name, $type)
    						}
    						else #Type info not found
    						{
    							[void]$table.Columns.Add($prop.Name)
    						}
    					}
    				}
    				
    				if ($object -is [System.Data.DataRow])
    				{
    					foreach ($item in $InputObject)
    					{
    						$Table.Rows.Add($item)
    					}
    					return @( ,$Table)
    				}
    			}
    			else
    			{
    				$Table.Rows.Clear()
    			}
    			
    			foreach ($item in $InputObject)
    			{
    				$row = $table.NewRow()
    				
    				if ($item)
    				{
    					foreach ($prop in $item.PSObject.Get_Properties())
    					{
    						if ($table.Columns.Contains($prop.Name))
    						{
    							$row.Item($prop.Name) = $prop.Value
    						}
    					}
    				}
    				[void]$table.Rows.Add($row)
    			}
    		}
    		
    		return @(,$Table)	
    	}
    	
    	
    	
    	$button1_Click={
    		
    		
    		$mbperms = get-mailbox $textbox1.Text | Get-MailboxPermission | ? { $_.user -notmatch "nt " }
    		
    		Load-DataGridView $datagridview1 $mbperms
    		
    		
    	}
    	
    	# --End User Generated Script--
    	#----------------------------------------------
    	#region Generated Events
    	#----------------------------------------------
    	
    	$Form_StateCorrection_Load=
    	{
    		#Correct the initial state of the form to prevent the .Net maximized form issue
    		$form1.WindowState = $InitialFormWindowState
    	}
    	
    	$Form_Cleanup_FormClosed=
    	{
    		#Remove all event handlers from the controls
    		try
    		{
    			$button1.remove_Click($button1_Click)
    			$form1.remove_Load($form1_Load)
    			$form1.remove_Load($Form_StateCorrection_Load)
    			$form1.remove_FormClosed($Form_Cleanup_FormClosed)
    		}
    		catch [Exception]
    		{ }
    	}
    	#endregion Generated Events
    
    	#----------------------------------------------
    	#region Generated Form Code
    	#----------------------------------------------
    	$form1.SuspendLayout()
    	#
    	# form1
    	#
    	$form1.Controls.Add($textbox1)
    	$form1.Controls.Add($button1)
    	$form1.Controls.Add($datagridview1)
    	$form1.AutoScaleDimensions = '6, 13'
    	$form1.AutoScaleMode = 'Font'
    	$form1.ClientSize = '583, 374'
    	$form1.Name = 'form1'
    	$form1.Text = 'Form'
    	$form1.add_Load($form1_Load)
    	#
    	# textbox1
    	#
    	$textbox1.Location = '25, 46'
    	$textbox1.Name = 'textbox1'
    	$textbox1.Size = '218, 20'
    	$textbox1.TabIndex = 2
    	#
    	# button1
    	#
    	$button1.Location = '266, 43'
    	$button1.Name = 'button1'
    	$button1.Size = '75, 23'
    	$button1.TabIndex = 1
    	$button1.Text = 'button1'
    	$button1.UseVisualStyleBackColor = $True
    	$button1.add_Click($button1_Click)
    	#
    	# datagridview1
    	#
    	$datagridview1.ColumnHeadersHeightSizeMode = 'AutoSize'
    	$datagridview1.Location = '25, 96'
    	$datagridview1.Name = 'datagridview1'
    	$datagridview1.Size = '514, 238'
    	$datagridview1.TabIndex = 0
    	$form1.ResumeLayout()
    	#endregion Generated Form Code
    
    	#----------------------------------------------
    
    	#Save the initial state of the form
    	$InitialFormWindowState = $form1.WindowState
    	#Init the OnLoad event to correct the initial state of the form
    	$form1.add_Load($Form_StateCorrection_Load)
    	#Clean up the control events
    	$form1.add_FormClosed($Form_Cleanup_FormClosed)
    	#Show the Form
    	return $form1.ShowDialog()
    
    } #End Function
    
    #Call the form
    Call-sapienexamples_psf | Out-Null
    
    
    
  • #51601
    Profile photo of Mark Prior
    Mark Prior
    Participant

    Thanks for this Dan, Have picked some pieces from your example and got mine working just how i want, will also join the sapien forums,

    C & Vb is not something i have used before

You must be logged in to reply to this topic.