textbox - browse for file problem

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
bn2hunt
Posts: 101
Joined: Tue Oct 06, 2009 12:08 am

textbox - browse for file problem

Post by bn2hunt » Thu Oct 22, 2015 5:19 am

I am using 64bit powershell studio 2015 version 4.2.95

64bit windows 8

I am able to browse for a file and put that filename and path into a datagrid. The problem I am having is when I try to access the file that I picked. I keep getting an invalid path error when I try to copy/move the file. And test-path doesn't find it.

How do I access the file after using the browse for file?

Thanks

User avatar
SAPIEN Support Forums
Posts: 945
Joined: Wed Dec 03, 2014 2:26 pm

textbox - browse for file problem

Post by SAPIEN Support Forums » Thu Oct 22, 2015 5:19 am

This is an automated post. A real person will respond soon.

Thank you for posting, bn2hunt.

Here are some hints to help you get an accurate and complete answer to your question.

Ask in the best forum: If you asked in the wrong forum, just copy your question to the right forum.

Anticipate follow-up questions!

Did you remember to include the following?
  • 1. Product, version and build
    2. 32 or 64 bit product
    3. Operating system, e.g. Windows 7 64 bit.
    4. Attach a screenshot, if applicable
    5. Attach logs, crash reports, etc., in a ZIP file
If not, please take a moment to edit your original post or reply to this one.

*** Make sure you do not post any licensing information ***

User avatar
bn2hunt
Posts: 101
Joined: Tue Oct 06, 2009 12:08 am

Re: textbox - browse for file problem(update)

Post by bn2hunt » Thu Oct 22, 2015 5:27 am

I am getting the same error if I hard code the path into the variable. If I move the code I am using, to a stand alone script it works as anticipated.
Last edited by bn2hunt on Thu Oct 22, 2015 5:33 am, edited 1 time in total.

jvierra
Posts: 13882
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: textbox - browse for file problem

Post by jvierra » Thu Oct 22, 2015 5:29 am

Unfortunately there is not enough information to understand you issues. We cannot see the code you are using and it is not possible too guess at what you are doing.

User avatar
bn2hunt
Posts: 101
Joined: Tue Oct 06, 2009 12:08 am

Re: textbox - browse for file problem

Post by bn2hunt » Thu Oct 22, 2015 5:41 am

Sorry, I was sanitizing server names. Her is the code

Code: Select all



$MainForm_Load={
	#TODO: Initialize Form Controls here
	load_sql_users
	load_sql_groups
	
}


#region Control Helper Functions
function Load-DataGridView
{
	<#
	.SYNOPSIS
		This functions helps you load items into a DataGridView.

	.DESCRIPTION
		Use this function to dynamically load items into the DataGridView control.

	.PARAMETER  DataGridView
		The DataGridView control you want to add items to.

	.PARAMETER  Item
		The object or objects you wish to load into the DataGridView's items collection.
	
	.PARAMETER  DataMember
		Sets the name of the list or table in the data source for which the DataGridView is displaying data.

	#>
	Param (
		[ValidateNotNull()]
		[Parameter(Mandatory=$true)]
		[System.Windows.Forms.DataGridView]$DataGridView,
		[ValidateNotNull()]
		[Parameter(Mandatory=$true)]
		$Item,
	    [Parameter(Mandatory=$false)]
		[string]$DataMember
	)
	$DataGridView.SuspendLayout()
	$DataGridView.DataMember = $DataMember
	
	if ($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
	}
	
	$DataGridView.ResumeLayout()
}

function ConvertTo-DataTable
{
	<#
		.SYNOPSIS
			Converts objects into a DataTable.
	
		.DESCRIPTION
			Converts objects into a DataTable, which are used for DataBinding.
	
		.PARAMETER  InputObject
			The input to convert into a DataTable.
	
		.PARAMETER  Table
			The DataTable you wish to load the input into.
	
		.PARAMETER RetainColumns
			This switch tells the function to keep the DataTable's existing columns.
		
		.PARAMETER FilterWMIProperties
			This switch removes WMI properties that start with an underline.
	
		.EXAMPLE
			$DataTable = ConvertTo-DataTable -InputObject (Get-Process)
	#>
	[OutputType([System.Data.DataTable])]
	param(
	[ValidateNotNull()]
	$InputObject, 
	[ValidateNotNull()]
	[System.Data.DataTable]$Table,
	[switch]$RetainColumns,
	[switch]$FilterWMIProperties)
	
	if($Table -eq $null)
	{
		$Table = New-Object System.Data.DataTable
	}

	if($InputObject-is [System.Data.DataTable])
	{
		$Table = $InputObject
	}
	else
	{
		if(-not $RetainColumns -or $Table.Columns.Count -eq 0)
		{
			#Clear out the Table Contents
			$Table.Clear()

			if($InputObject -eq $null){ return } #Empty Data
			
			$object = $null
			#server1d the first non null value
			foreach($item in $InputObject)
			{
				if($item -ne $null)
				{
					$object = $item
					break	
				}
			}

			if($object -eq $null) { 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 Deserver1ition string
					$type = $null
					
					if($prop.Value -ne $null)
					{
						try{ $type = $prop.Value.GetType() } catch {}
					}

					if($type -ne $null) # -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)	
}

function Sort-ListViewColumn 
{
	<#
	.SYNOPSIS
		Sort the ListView's item using the specified column.

	.DESCRIPTION
		Sort the ListView's item using the specified column.
		This function uses Add-Type to deserver1e a class that sort the items.
		The ListView's Tag property is used to keep track of the sorting.

	.PARAMETER ListView
		The ListView control to sort.

	.PARAMETER ColumnIndex
		The index of the column to use for sorting.
		
	.PARAMETER  SortOrder
		The direction to sort the items. If not specified or set to None, it will toggle.
	
	.EXAMPLE
		Sort-ListViewColumn -ListView $listview1 -ColumnIndex 0
#>
	param(	
			[ValidateNotNull()]
			[Parameter(Mandatory=$true)]
			[System.Windows.Forms.ListView]$ListView,
			[Parameter(Mandatory=$true)]
			[int]$ColumnIndex,
			[System.Windows.Forms.SortOrder]$SortOrder = 'None')
	
	if(($ListView.Items.Count -eq 0) -or ($ColumnIndex -lt 0) -or ($ColumnIndex -ge $ListView.Columns.Count))
	{
		return;
	}
	
	#region Deserver1e ListViewItemComparer
		try{
		$local:type = [ListViewItemComparer]
	}
	catch{
	Add-Type -ReferencedAssemblies ('System.Windows.Forms') -TypeDeserver1ition  @" 
	using System;
	using System.Windows.Forms;
	using System.Collections;
	public class ListViewItemComparer : IComparer
	{
	    public int column;
	    public SortOrder sortOrder;
	    public ListViewItemComparer()
	    {
	        column = 0;
			sortOrder = SortOrder.Ascending;
	    }
	    public ListViewItemComparer(int column, SortOrder sort)
	    {
	        this.column = column;
			sortOrder = sort;
	    }
	    public int Compare(object x, object y)
	    {
			if(column >= ((ListViewItem)x).SubItems.Count)
				return  sortOrder == SortOrder.Ascending ? -1 : 1;
		
			if(column >= ((ListViewItem)y).SubItems.Count)
				return sortOrder == SortOrder.Ascending ? 1 : -1;
		
			if(sortOrder == SortOrder.Ascending)
	        	return String.Compare(((ListViewItem)x).SubItems[column].Text, ((ListViewItem)y).SubItems[column].Text);
			else
				return String.Compare(((ListViewItem)y).SubItems[column].Text, ((ListViewItem)x).SubItems[column].Text);
	    }
	}
"@  | Out-Null
	}
	#endregion
	
	if($ListView.Tag -is [ListViewItemComparer])
	{
		#Toggle the Sort Order
		if($SortOrder -eq [System.Windows.Forms.SortOrder]::None)
		{
			if($ListView.Tag.column -eq $ColumnIndex -and $ListView.Tag.sortOrder -eq 'Ascending')
			{
				$ListView.Tag.sortOrder = 'Descending'
			}
			else
			{
				$ListView.Tag.sortOrder = 'Ascending'
			}
		}
		else
		{
			$ListView.Tag.sortOrder = $SortOrder
		}
		
		$ListView.Tag.column = $ColumnIndex
		$ListView.Sort()#Sort the items
	}
	else
	{
		if($SortOrder -eq [System.Windows.Forms.SortOrder]::None)
		{
			$SortOrder = [System.Windows.Forms.SortOrder]::Ascending	
		}
		
		#Set to Tag because for some reason in PowerShell ListViewItemSorter prop returns null
		$ListView.Tag = New-Object ListViewItemComparer ($ColumnIndex, $SortOrder) 
		$ListView.ListViewItemSorter = $ListView.Tag #Automatically sorts
	}
}


function Add-ListViewItem
{
<#
	.SYNOPSIS
		Adds the item(s) to the ListView and stores the object in the ListViewItem's Tag property.

	.DESCRIPTION
		Adds the item(s) to the ListView and stores the object in the ListViewItem's Tag property.

	.PARAMETER ListView
		The ListView control to add the items to.

	.PARAMETER Items
		The object or objects you wish to load into the ListView's Items collection.
		
	.PARAMETER  ImageIndex
		The index of a predeserver1ed image in the ListView's ImageList.
	
	.PARAMETER  SubItems
		List of strings to add as Subitems.
	
	.PARAMETER Group
		The group to place the item(s) in.
	
	.PARAMETER Clear
		This switch clears the ListView's Items before adding the new item(s).
	
	.EXAMPLE
		Add-ListViewItem -ListView $listview1 -Items "Test" -Group $listview1.Groups[0] -ImageIndex 0 -SubItems "Installed"
#>
	
	Param( 
	[ValidateNotNull()]
	[Parameter(Mandatory=$true)]
	[System.Windows.Forms.ListView]$ListView,
	[ValidateNotNull()]
	[Parameter(Mandatory=$true)]
	$Items,
	[int]$ImageIndex = -1,
	[string[]]$SubItems,
	$Group,
	[switch]$Clear)
	
	if($Clear)
	{
		$ListView.Items.Clear();
    }
    
    $lvGroup = $null
    if ($Group -is [System.Windows.Forms.ListViewGroup])
    {
        $lvGroup = $Group
    }
    elseif ($Group -is [string])
    {
        #$lvGroup = $ListView.Group[$Group] # Case sensitive
        foreach ($groupItem in $ListView.Groups)
        {
            if ($groupItem.Name -eq $Group)
            {
                $lvGroup = $groupItem
                break
            }
        }
        
        if ($lvGroup -eq $null)
        {
            $lvGroup = $ListView.Groups.Add($Group, $Group)
        }
    }
    
	if($Items -is [Array])
	{
		$ListView.BeginUpdate()
		foreach ($item in $Items)
		{		
			$listitem  = $ListView.Items.Add($item.ToString(), $ImageIndex)
			#Store the object in the Tag
			$listitem.Tag = $item
			
			if($SubItems -ne $null)
			{
				$listitem.SubItems.AddRange($SubItems)
			}
			
			if($lvGroup -ne $null)
			{
				$listitem.Group = $lvGroup
			}
		}
		$ListView.EndUpdate()
	}
	else
	{
		#Add a new item to the ListView
		$listitem  = $ListView.Items.Add($Items.ToString(), $ImageIndex)
		#Store the object in the Tag
		$listitem.Tag = $Items
		
		if($SubItems -ne $null)
		{
			$listitem.SubItems.AddRange($SubItems)
		}
		
		if($lvGroup -ne $null)
		{
			$listitem.Group = $lvGroup
		}
	}
}

function Load-ListBox 
{
<#
	.SYNOPSIS
		This functions helps you load items into a ListBox or CheckedListBox.

	.DESCRIPTION
		Use this function to dynamically load items into the ListBox control.

	.PARAMETER  ListBox
		The ListBox control you want to add items to.

	.PARAMETER  Items
		The object or objects you wish to load into the ListBox's Items collection.

	.PARAMETER  DisplayMember
		Indicates the property to display for the items in this control.
	
	.PARAMETER  Append
		Adds the item(s) to the ListBox without clearing the Items collection.
	
	.EXAMPLE
		Load-ListBox $ListBox1 "Red", "White", "Blue"
	
	.EXAMPLE
		Load-ListBox $listBox1 "Red" -Append
		Load-ListBox $listBox1 "White" -Append
		Load-ListBox $listBox1 "Blue" -Append
	
	.EXAMPLE
		Load-ListBox $listBox1 (Get-Process) "ProcessName"
#>
	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])
	{
		$listBox.Items.AddRange($Items)
	}
	elseif ($Items -is [Array])
	{
		$listBox.BeginUpdate()
		foreach($obj in $Items)
		{
			$listBox.Items.Add($obj)
		}
		$listBox.EndUpdate()
	}
	else
	{
		$listBox.Items.Add($Items)	
	}

	$listBox.DisplayMember = $DisplayMember	
}

function Load-ComboBox 
{
<#
	.SYNOPSIS
		This functions helps you load items into a ComboBox.

	.DESCRIPTION
		Use this function to dynamically load items into the ComboBox control.

	.PARAMETER  ComboBox
		The ComboBox control you want to add items to.

	.PARAMETER  Items
		The object or objects you wish to load into the ComboBox's Items collection.

	.PARAMETER  DisplayMember
		Indicates the property to display for the items in this control.
	
	.PARAMETER  Append
		Adds the item(s) to the ComboBox without clearing the Items collection.
	
	.EXAMPLE
		Load-ComboBox $combobox1 "Red", "White", "Blue"
	
	.EXAMPLE
		Load-ComboBox $combobox1 "Red" -Append
		Load-ComboBox $combobox1 "White" -Append
		Load-ComboBox $combobox1 "Blue" -Append
	
	.EXAMPLE
		Load-ComboBox $combobox1 (Get-Process) "ProcessName"
#>
	Param (
		[ValidateNotNull()]
		[Parameter(Mandatory=$true)]
		[System.Windows.Forms.ComboBox]$ComboBox,
		[ValidateNotNull()]
		[Parameter(Mandatory=$true)]
		$Items,
	    [Parameter(Mandatory=$false)]
		[string]$DisplayMember,
		[switch]$Append
	)
	
	if(-not $Append)
	{
		$ComboBox.Items.Clear()	
	}
	
	if($Items -is [Object[]])
	{
		$ComboBox.Items.AddRange($Items)
	}
	elseif ($Items -is [Array])
	{
		$ComboBox.BeginUpdate()
		foreach($obj in $Items)
		{
			$ComboBox.Items.Add($obj)	
		}
		$ComboBox.EndUpdate()
	}
	else
	{
		$ComboBox.Items.Add($Items)	
	}

	$ComboBox.DisplayMember = $DisplayMember	
}
#endregion

function load_sql_users
{
	$x = Invoke-Sqlcmd -ServerInstance server1\rms -Database attachlog -Query "select name from userlist order by name"
	$x_cntr = "1"
	
	foreach ($item in $x)
	{
		if ($x_cntr -eq "1")
		{
			Load-ListBox $LB_userlist $item.name
			$x_cntr = "2"
		}
		else
		{
			Load-ListBox $LB_userlist $item.name -Append
		}
	}
}

function load_sql_groups
{
	$x1 = Invoke-Sqlcmd -ServerInstance server1\rms -Query "Select syslogins.loginname From syslogins"
	$x1_cntr = "1"
	
	foreach ($item in $x1)
	{
		$lname = $item.loginname
		$lname = $lname.substring(0, 2)
		switch ($lname)
		{
			"##" 	{"do nothing"}
			"nt"	{"do nothing"}
			default
			{
				if ($x1_cntr -eq "1")
				{
					Load-ListBox $chk_lb_groups $item.loginname
					$x1_cntr = "2"
				}
				else
				{
					Load-ListBox $chk_lb_groups $item.loginname -Append
				}
			}
		}
	}
}

function copydb
{
	if (Test-Path $mdffiles)
	{ Write-Host "file already exists on server" }
	else
	{move-Item -Path $dbfullname -Destination $copy2 }
	
	
	
	Write-Host $dbfullname
		write-host "\\server1\g\loc3_scripts\loc3_data\loc3\attachlog.mdf"
		write-host $copy2
		write-host "\\server2\d$\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
}

function attach_db
{
	
	$sqlcmd = "create database $dbname on (filename = '$mdffiles') for ATTACH"
	$x = Invoke-Sqlcmd -ServerInstance server2 -Query $sqlcmd

}

function sp_owner
{
	
}

$CB_attach_detach_SelectedIndexChanged = {
	#TODO: Place custom script here
	if ($CB_attach_detach.text = "Attach")
	{ $LB_userlist.enabled = $true }
	else
	{ Write-Host $CB_attach_detach.text }
	
}

$RB_Attach_CheckedChanged={
	#TODO: Place custom script here
	$LB_userlist.Enabled = $true
	$TB_filebrowser.Enabled = $true
	$btn_Browse.Enabled = $true
	$tabpage1.Enabled = $true
	$tabpage2.Enabled = $false
	$tabpage3.Enabled = $false
	$tabcontrol1.SelectedTab = $tabpage1
}

$RB_Detach_CheckedChanged={
	#TODO: Place custom script here
	$LB_userlist.Enabled = $true
	$TB_filebrowser.Enabled = $false
	$btn_Browse.Enabled = $false
	$tabpage1.Enabled = $false
	$tabpage2.Enabled = $true
	$tabpage3.Enabled = $false
	$tabcontrol1.SelectedTab = $tabpage2
}

$btn_Browse_Click= {
	$openfiledialog1.filter = "my file|*.mdf;*.zip;*.rar|SQL Database files(*.mdf)|*.mdf | all files|*.*"
	$openfiledialog1.initialdirectory = "\\server1\g\loc3_scripts\loc3_data"
	$openfiledialog1.Multiselect = $false
	$openfiledialog1.RestoreDirectory = $true
	$errind = $false
	
	if ($openfiledialog1.ShowDialog() -eq 'OK')
	{
		$flname = $openfiledialog1.FileName
		Write-Host $openfiledialog1.SafeFileName
		Write-Host $openfiledialog1.CheckFileExists
		$TB_filebrowser.Text = $flname
	}
	
	if ($flname.Length -ge 1)
	{
		$ext = $flname.Substring($flname.LastIndexOfAny(".")+1)
		$flname = $flname.Substring($flname.LastIndexOfAny("\") + 1)
		$flname = $flname.Substring(0, $flname.LastIndexOfAny("."))
	}
	ELSE
	{
		$errind = $true
	}
	
	if ($ext -eq "zip")
	{
		#start winzip
	}
	else
	{
		if ($chk_lb_groups.CheckedItems -ge 1)
		{
			foreach ($xi in $chk_lb_groups.CheckedItems) { $grps = $grps + $xi + "," }
			$grps = $grps.substring(0, $grps.length - 1)
		}
		ELSE
		{
			$errind = $true
		}
	}
	
	if ($errind -eq $false)
	{
		
		if (Test-Path $openfiledialog1.FileName) { Write-Host "yup" } else { Write-Host "nope" }
		$values = $flname, $openfiledialog1.FileName, $LB_userlist.Text, $grps
	
		$datagridview1.Rows.Add($values)
	}
	
}

$btn_GO_Click= {
	#TODO: Place custom script here
	for ($i = 0; $i -lt $datagridview1.RowCount-1; $i++)
	{
		$dbname = $datagridview1.Rows[$i].Cells[0].FormattedValue
		$dbfullname = $datagridview1.Rows[$i].Cells[1].FormattedValue
		$1a = $datagridview1.Rows[$i].Cells[1].FormattedValueType
		Write-Host $1a
		
		
		$attached4 =  $datagridview1.Rows[$i].Cells[2].Value
		$grouplist = $datagridview1.Rows[$i].Cells[3].Value
		
		$copy2 = "\\server2\d$\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
		$mdfloc = "d:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
		$instance = "server2"
		
		$flname = $dbfullname.Substring($dbfullname.LastIndexOfAny("\") + 1)

		Write-Host "$dbname,$dbfullname,$attached4,$grouplist"
		$mdffiles = $mdfloc + $flname
		#copydb
		
		if (Test-Path $mdffiles)
		{ Write-Host "file already exists on server" }
		else
		{move-Item -Path $dbfullname -Destination $copy2 }
		#attach_db
		$eachgroupinlist = $grouplist.Split(",")
		ForEach ($grpinlist in $eachgroupinlist)
		{
			$owner = $grpinlist
			#sp_owner
			Write-Host $owner	
		}
	}
}


jvierra
Posts: 13882
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: textbox - browse for file problem

Post by jvierra » Thu Oct 22, 2015 5:59 am

Can you please just post the PSF file or post a stripped down version that shows the issue you are having.

99% of what you have posted has nothing to do with file paths.

User avatar
bn2hunt
Posts: 101
Joined: Tue Oct 06, 2009 12:08 am

Re: textbox - browse for file problem

Post by bn2hunt » Thu Oct 22, 2015 6:13 am

The move-item in this code is the specific code where I am getting the error. It doesn't seem to matter if I hard code the path and destination in a variable or if I use the location I get from the browse function.

Code: Select all

function copydb
	{
		if (Test-Path $mdffiles)
		{ Write-Host "file already exists on server" }
		else
		{move-Item -Path $dbfullname -Destination $copy2 }
	}
	
	
	
	$btn_Browse_Click= {
		$openfiledialog1.filter = "my file|*.mdf;*.zip;*.rar|SQL Database files(*.mdf)|*.mdf | all files|*.*"
		$openfiledialog1.initialdirectory = "\\server1\g\loc1_scripts\loc1_data"
		$openfiledialog1.Multiselect = $false
		$openfiledialog1.RestoreDirectory = $true
		$errind = $false
		
		if ($openfiledialog1.ShowDialog() -eq 'OK')
		{
			$flname = $openfiledialog1.FileName
			$TB_filebrowser.Text = $flname
		}
		
		if ($flname.Length -ge 1)
		{
			$ext = $flname.Substring($flname.LastIndexOfAny(".")+1)
			$flname = $flname.Substring($flname.LastIndexOfAny("\") + 1)
			$flname = $flname.Substring(0, $flname.LastIndexOfAny("."))
		}
			
		$values = $flname, $openfiledialog1.FileName, $LB_userlist.Text, $grps
		
		$datagridview1.Rows.Add($values)
		}
		
	}
	
	$btn_GO_Click= {
		#TODO: Place custom script here
		for ($i = 0; $i -lt $datagridview1.RowCount-1; $i++)
		{
			$dbname = $datagridview1.Rows[$i].Cells[0].Value
			$dbfullname = $datagridview1.Rows[$i].Cells[1].Value
			$attached4 =  $datagridview1.Rows[$i].Cells[2].Value
			$grouplist = $datagridview1.Rows[$i].Cells[3].Value
			
			$copy2 = "\\server2\d$\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
			$mdfloc = "d:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"
			$instance = "server2"
			
			$flname = $dbfullname.Substring($dbfullname.LastIndexOfAny("\") + 1)
			$mdffiles = $mdfloc + $flname
			copydb
			attach_db
			
		}
	}

User avatar
bn2hunt
Posts: 101
Joined: Tue Oct 06, 2009 12:08 am

Re: textbox - browse for file problem

Post by bn2hunt » Thu Oct 22, 2015 6:18 am

This doesn't even work, I am getting the invalid path on the "\\server1\g\loc1_scripts\loc1_data\loc1\attachlog.mdf". But a non-gui script the same code works.

Code: Select all

move-Item -Path "\\server1\g\loc1_scripts\loc1_data\loc1\attachlog.mdf" -Destination "\\server2\d$\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\"}

jvierra
Posts: 13882
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: textbox - browse for file problem

Post by jvierra » Thu Oct 22, 2015 6:24 am

This should help you to find you bugs.
PowerShell Code
Double-click the code block to select all.
function copydb {
	Param (
		[Parameter(Mandatory=$true)]$mdffiles,
		[Parameter(Mandatory=$true)]$dbfullname,
		[Parameter(Mandatory=$true)]$copy2
	)
	if (Test-Path $mdffiles) {
		Write-Host "file already exists on server"
	} else {
		Try{
			move-Item -Path $dbfullname -Destination $copy2 -ea Stop
		} Catch {
			[void][System.Windows.Forms.MessageBox]::Show("$_",'ERROR')
        }
	}
}



$btn_Browse_Click = {
	$openfiledialog1.filter = "my file|*.mdf;*.zip;*.rar|SQL Database files(*.mdf)|*.mdf | all files|*.*"
	$openfiledialog1.initialdirectory = "\\server1\g\loc1_scripts\loc1_data"
	$openfiledialog1.Multiselect = $false
	$openfiledialog1.RestoreDirectory = $true
	$errind = $false
	
	if ($openfiledialog1.ShowDialog() -eq 'OK') {
		$flname = $openfiledialog1.FileName
		$TB_filebrowser.Text = $flname
	}
	
	if ($flname.Length -ge 1) {
		$ext = $flname.Substring($flname.LastIndexOfAny(".") + 1)
		$flname = $flname.Substring($flname.LastIndexOfAny("\") + 1)
		$flname = $flname.Substring(0, $flname.LastIndexOfAny("."))
	}
	
	$values = $flname, $openfiledialog1.FileName, $LB_userlist.Text, $grps
	
	$datagridview1.Rows.Add($values)
}

}

$btn_GO_Click = {
	#TODO: Place custom script here
	for ($i = 0; $i -lt $datagridview1.RowCount - 1; $i++) {
		$dbname = $datagridview1.Rows[$i].Cells[0].Value
		$dbfullname = $datagridview1.Rows[$i].Cells[1].Value
		$attached4 = $datagridview1.Rows[$i].Cells[2].Value
		$grouplist = $datagridview1.Rows[$i].Cells[3].Value
		
		$copy2 = '\\server2\d$\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\'
		$mdfloc = 'd:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\'
		$instance = "server2"
		
		$flname = $dbfullname.Substring($dbfullname.LastIndexOfAny("\") + 1)
		$mdffiles = $mdfloc + $flname
		copydb -mdffiles $mdfloc -dbfullname $flname -copy2 $copy2
		attach_db
		
	}
}

User avatar
bn2hunt
Posts: 101
Joined: Tue Oct 06, 2009 12:08 am

Re: textbox - browse for file problem

Post by bn2hunt » Thu Oct 22, 2015 11:23 am

It is giving me the following error on the copy

Cannot retrieve the dynamic parameters for the cmdlet. SQL server powershell provider error: Path SQLSERVER:\database.mdf does not exist. Please specify a valid path.

Locked