<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
		>
<channel>
	<title>Comments for using Hagen.Frank.blog;</title>
	<atom:link href="http://fwhagen.wordpress.com/comments/feed/" rel="self" type="application/rss+xml" />
	<link>http://fwhagen.wordpress.com</link>
	<description>// Frank Hagen: Professional Web Developer, C# User, Uber-geek Wannabe</description>
	<lastBuildDate>Fri, 26 Jun 2009 20:18:29 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>Comment on QuerySQL.ps1 by Fitz</title>
		<link>http://fwhagen.wordpress.com/querysqlps1/#comment-667</link>
		<dc:creator>Fitz</dc:creator>
		<pubDate>Fri, 26 Jun 2009 20:18:29 +0000</pubDate>
		<guid isPermaLink="false">http://fwhagen.wordpress.com/?page_id=175#comment-667</guid>
		<description>Your blog is truncating the right hand side of the script.... 


################################################################################
#   QuerySQL.ps1                                   # Frank W Hagen - 2008/07/15
#                                                  #   FWHagen.wordpress.com
#     Powershell script to query a SQL database    #   fwhagen.blog@gmail.com
#      and write the output to an Excel file
#
#     Usage:
#     * Create a SQL query file by putting a valid SQL query in a text file in
#       the subdirectory specified in $SQLQueryPath named .sql
#     * Set configuration variables in config section below
#     * Run at command line:  powershell -nologo .\QuerySQL.ps1
#         OR right-click this script and Open With -&gt; Powershell.EXE
#
#     If you get a security warning running the script, see the following post:
#     http://fwhagen.wordpress.com/2007/10/29/running-local-powershell-scripts/
################################################################################

# Function used for binding to Excel
function Invoke([object]$m, [string]$method, $parameters)
{  $m.PSBase.GetType().InvokeMember($method, [Reflection.BindingFlags]::InvokeMethod, $null, $m, $parameters, [System.Globalization.CultureInfo]&quot;en-US&quot;)  } 

######################################################
### Configuration information for specific query #####
$TaskName = &quot;AllCompletedWithCosts&quot;     # Title and name of query file
$SqlServer = &quot;SQLServerName&quot;;           # SQL Server
$SqlCatalog = &quot;MyDatabase&quot;;             # Database name
$WriteOutXML = $False
$WriteOutCSV = $False
$WriteOutXLS = $True
#
# Environment Configuration
$TaskPath = &quot;C:\DEV\_sql\Reports\&quot;          # Root Directory for creating reports
$SQLQueryPath = &quot;SQLQueries\&quot;               # Subdirectory for finding the queryfile
######################################################

# Timestamp the output folder and files using ISOdate
$OutPath = ($TaskPath + (Get-Date -Format yyyyMMdd) + &quot;-&quot; + $TaskName + &quot;\&quot;)
$OutFileName = ( (Get-Date -Format yyyyMMdd) + &quot;-&quot; + $TaskName )

# Create the output folder                                      #TODO: Fix Call to eliminate verbose results from system
if (!$(test-path ($OutPath)))
{
    New-Item -itemType directory -Name ((Get-Date -Format yyyyMMdd) + &quot;-&quot; + $TaskName) &gt; $null

    if ($(test-path ($OutPath)))
    {
        Write-Host ($OutPath + &quot; Created&quot;) -ForegroundColor &quot;darkgreen&quot;
    }
    else
    {
        Write-Host ($OutPath + &quot; FAILED&quot;) -ForegroundColor &quot;red&quot;
    }
}

# Get the T-SQL Query from .SQL file
$SqlQuery = Get-Content ($TaskPath + $SQLQueryPath + $TaskName + &quot;.sql&quot;)
Write-Host (&quot;Executing Queryfile: &quot; + ($TaskName + &quot;.sql&quot;) + &quot; &quot;) -ForegroundColor &quot;darkgreen&quot;
#Write-Host ($SqlQuery) -ForegroundColor &quot;gray&quot;

# Setup SQL Connection (using Integrated Security (your workstation login).  Use standard connection string format for other)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = &quot;Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True&quot;

# Setup SQL Command
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

# Setup .NET SQLAdapter to execute and fill .NET Dataset
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$DataTable = New-Object System.Data.DataTable

# Execute and Get Row Count
$nRecs = $SqlAdapter.Fill($DataSet)

Write-Host ($nRecs.ToString() + &quot; Records retrieved.&quot;) -ForegroundColor &quot;Blue&quot;
$SqlConnection.Close();

if ($nRecs -gt 0)
{
    # Make copy of successful query in output directory for traceability
    if ($(test-path ($OutPath + $OutFileName + &quot;.sql&quot;)))
    {
        del ($OutPath + $OutFileName + &quot;.sql&quot;)
    }
    Copy-Item ($TaskPath + $SQLQueryPath + $TaskName + &quot;.sql&quot;) -destination ($OutPath + $OutFileName + &quot;.sql&quot;)

    # Very simple to export XML
    if($WriteOutXML)
    {
        Write-Host &quot;Creating XML File...&quot; -ForegroundColor &quot;darkgreen&quot;
        if ($(test-path ($OutPath + $OutFileName + &quot;.xml&quot;)))
        {
            del ($OutPath + $OutFileName + &quot;.xml&quot;)
        }

        $DataSet.Tables[0].WriteXML($OutPath + $OutFileName + &quot;.xml&quot;);
    }

    # Very simple to export CSV
    if($WriteOutCSV)
    {
        Write-Host &quot;Creating CSV File...&quot; -ForegroundColor &quot;darkgreen&quot;
        if ($(test-path ($OutPath + $OutFileName + &quot;.csv&quot;)))
        {
            del ($OutPath + $OutFileName + &quot;.csv&quot;)
        }

        $DataSet.Tables[0] &#124; Export-Csv ($OutPath + $OutFileName + &quot;.csv&quot;)
    }

    # Very hard to export XSL - This method writes the data to an object array and pastes the array directly into Excel  (Thanks go to a few sources on the Internet for this method)
    if($WriteOutXLS)
    {
        Write-Host &quot;Creating Excel File...&quot; -ForegroundColor &quot;darkgreen&quot;
        if ($(test-path ($OutPath + $OutFileName + &quot;.xls&quot;)))
        {
            del ($OutPath + $OutFileName + &quot;.xls&quot;)
        }

        $sheetIndex = 0;
        $oExcel = New-Object -COM Excel.Application
        $oExcel.Visible = $false
        $oBooks = $oExcel.Workbooks
        $oCulture= [System.Globalization.CultureInfo]&quot;en-US&quot;
        $oBook=$oBooks.psbase.gettype().InvokeMember(&quot;Add&quot;,[Reflection.BindingFlags]::InvokeMethod,$null,$oBooks,$null,$oCulture)
        #$oSheet = $oBook.Worksheets.Item(1)

        $DataTable = $DataSet.Tables[0];
        $nDr = $DataTable.Rows.Count + 1
        $nDc = $DataTable.Columns.Count + 1

        # Create the object array
        $rawData = new-object &#039;object[,]&#039; $nDr,$nDc  

        # Write the field names in the first row
        for ($col = 0; $col -lt $DataTable.Columns.Count; $col++)
        {
            $rawData[0, $col] = $DataTable.Columns[$col].ColumnName;
        }

        # Copy the dataset to the object array
        for ($col = 0; $col -lt $DataTable.Columns.Count; $col++)
        {
            for ($row = 0; $row -lt $DataTable.Rows.Count; $row++)
            {
                $rawData[($row + 1), $col] = $DataTable.Rows[$row][$col];
            }
        }

        # Calculate the final column letter
        $finalColLetter = &quot;&quot;;
        $colCharset = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;
        $colCharsetLen = $colCharset.Length;
        if ($DataTable.Columns.Count -gt $colCharsetLen)
        {
            $finalColLetter = $colCharset.Substring((($DataTable.Columns.Count - 1) / ($colCharsetLen - 1)), 1);
        }
        $finalColLetter += $colCharset.Substring(($DataTable.Columns.Count - 1) % $colCharsetLen, 1);

        ### Export it all to Excel #####
        Write-Host &quot;Writing to Excel...&quot; -ForegroundColor &quot;darkgreen&quot;

        # Create a new Sheet
        $excelSheet = $oBook.Worksheets.Item(1)

        #$excelSheet.name = $DataTable.TableName;               #TODO: Be nice to figure out how to make this work (not critical)

        # Create the entire range on the worksheet and dump the data into it
        $excelRange = &quot;A1:&quot; + $finalColLetter + &quot;&quot; + ($DataTable.Rows.Count + 1)
        $excelSheet.Range($excelRange).FormulaLocal = $rawData;

        # Mark the first row as BOLD                            #TODO: Be nice to figure out how to make this work (not critical)
        #$excelSheet.Rows[1].Font.Bold = $True;
        #$excelSheet.Cells.Item(1,1).Font.Bold = $True;

        # Save the Excel file and we&#039;re done
        Invoke $oBook SaveAs ($OutPath + $OutFileName + &quot;.xls&quot;) &gt; $null
        Invoke $oBook Close 0 &gt;$null
        $oExcel.Quit()
    }
}

Write-Host (&quot;Complete&quot;)</description>
		<content:encoded><![CDATA[<p>Your blog is truncating the right hand side of the script&#8230;. </p>
<p>################################################################################<br />
#   QuerySQL.ps1                                   # Frank W Hagen &#8211; 2008/07/15<br />
#                                                  #   FWHagen.wordpress.com<br />
#     Powershell script to query a SQL database    #   <a href="mailto:fwhagen.blog@gmail.com">fwhagen.blog@gmail.com</a><br />
#      and write the output to an Excel file<br />
#<br />
#     Usage:<br />
#     * Create a SQL query file by putting a valid SQL query in a text file in<br />
#       the subdirectory specified in $SQLQueryPath named .sql<br />
#     * Set configuration variables in config section below<br />
#     * Run at command line:  powershell -nologo .\QuerySQL.ps1<br />
#         OR right-click this script and Open With -&gt; Powershell.EXE<br />
#<br />
#     If you get a security warning running the script, see the following post:<br />
#     <a href="http://fwhagen.wordpress.com/2007/10/29/running-local-powershell-scripts/" rel="nofollow">http://fwhagen.wordpress.com/2007/10/29/running-local-powershell-scripts/</a><br />
################################################################################</p>
<p># Function used for binding to Excel<br />
function Invoke([object]$m, [string]$method, $parameters)<br />
{  $m.PSBase.GetType().InvokeMember($method, [Reflection.BindingFlags]::InvokeMethod, $null, $m, $parameters, [System.Globalization.CultureInfo]&#8220;en-US&#8221;)  } </p>
<p>######################################################<br />
### Configuration information for specific query #####<br />
$TaskName = &#8220;AllCompletedWithCosts&#8221;     # Title and name of query file<br />
$SqlServer = &#8220;SQLServerName&#8221;;           # SQL Server<br />
$SqlCatalog = &#8220;MyDatabase&#8221;;             # Database name<br />
$WriteOutXML = $False<br />
$WriteOutCSV = $False<br />
$WriteOutXLS = $True<br />
#<br />
# Environment Configuration<br />
$TaskPath = &#8220;C:\DEV\_sql\Reports\&#8221;          # Root Directory for creating reports<br />
$SQLQueryPath = &#8220;SQLQueries\&#8221;               # Subdirectory for finding the queryfile<br />
######################################################</p>
<p># Timestamp the output folder and files using ISOdate<br />
$OutPath = ($TaskPath + (Get-Date -Format yyyyMMdd) + &#8220;-&#8221; + $TaskName + &#8220;\&#8221;)<br />
$OutFileName = ( (Get-Date -Format yyyyMMdd) + &#8220;-&#8221; + $TaskName )</p>
<p># Create the output folder                                      #TODO: Fix Call to eliminate verbose results from system<br />
if (!$(test-path ($OutPath)))<br />
{<br />
    New-Item -itemType directory -Name ((Get-Date -Format yyyyMMdd) + &#8220;-&#8221; + $TaskName) &gt; $null</p>
<p>    if ($(test-path ($OutPath)))<br />
    {<br />
        Write-Host ($OutPath + &#8221; Created&#8221;) -ForegroundColor &#8220;darkgreen&#8221;<br />
    }<br />
    else<br />
    {<br />
        Write-Host ($OutPath + &#8221; FAILED&#8221;) -ForegroundColor &#8220;red&#8221;<br />
    }<br />
}</p>
<p># Get the T-SQL Query from .SQL file<br />
$SqlQuery = Get-Content ($TaskPath + $SQLQueryPath + $TaskName + &#8220;.sql&#8221;)<br />
Write-Host (&#8220;Executing Queryfile: &#8221; + ($TaskName + &#8220;.sql&#8221;) + &#8221; &#8220;) -ForegroundColor &#8220;darkgreen&#8221;<br />
#Write-Host ($SqlQuery) -ForegroundColor &#8220;gray&#8221;</p>
<p># Setup SQL Connection (using Integrated Security (your workstation login).  Use standard connection string format for other)<br />
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection<br />
$SqlConnection.ConnectionString = &#8220;Server = $SqlServer; Database = $SqlCatalog; Integrated Security = True&#8221;</p>
<p># Setup SQL Command<br />
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand<br />
$SqlCmd.CommandText = $SqlQuery<br />
$SqlCmd.Connection = $SqlConnection</p>
<p># Setup .NET SQLAdapter to execute and fill .NET Dataset<br />
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter<br />
$SqlAdapter.SelectCommand = $SqlCmd<br />
$DataSet = New-Object System.Data.DataSet<br />
$DataTable = New-Object System.Data.DataTable</p>
<p># Execute and Get Row Count<br />
$nRecs = $SqlAdapter.Fill($DataSet)</p>
<p>Write-Host ($nRecs.ToString() + &#8221; Records retrieved.&#8221;) -ForegroundColor &#8220;Blue&#8221;<br />
$SqlConnection.Close();</p>
<p>if ($nRecs -gt 0)<br />
{<br />
    # Make copy of successful query in output directory for traceability<br />
    if ($(test-path ($OutPath + $OutFileName + &#8220;.sql&#8221;)))<br />
    {<br />
        del ($OutPath + $OutFileName + &#8220;.sql&#8221;)<br />
    }<br />
    Copy-Item ($TaskPath + $SQLQueryPath + $TaskName + &#8220;.sql&#8221;) -destination ($OutPath + $OutFileName + &#8220;.sql&#8221;)</p>
<p>    # Very simple to export XML<br />
    if($WriteOutXML)<br />
    {<br />
        Write-Host &#8220;Creating XML File&#8230;&#8221; -ForegroundColor &#8220;darkgreen&#8221;<br />
        if ($(test-path ($OutPath + $OutFileName + &#8220;.xml&#8221;)))<br />
        {<br />
            del ($OutPath + $OutFileName + &#8220;.xml&#8221;)<br />
        }</p>
<p>        $DataSet.Tables[0].WriteXML($OutPath + $OutFileName + &#8220;.xml&#8221;);<br />
    }</p>
<p>    # Very simple to export CSV<br />
    if($WriteOutCSV)<br />
    {<br />
        Write-Host &#8220;Creating CSV File&#8230;&#8221; -ForegroundColor &#8220;darkgreen&#8221;<br />
        if ($(test-path ($OutPath + $OutFileName + &#8220;.csv&#8221;)))<br />
        {<br />
            del ($OutPath + $OutFileName + &#8220;.csv&#8221;)<br />
        }</p>
<p>        $DataSet.Tables[0] | Export-Csv ($OutPath + $OutFileName + &#8220;.csv&#8221;)<br />
    }</p>
<p>    # Very hard to export XSL &#8211; This method writes the data to an object array and pastes the array directly into Excel  (Thanks go to a few sources on the Internet for this method)<br />
    if($WriteOutXLS)<br />
    {<br />
        Write-Host &#8220;Creating Excel File&#8230;&#8221; -ForegroundColor &#8220;darkgreen&#8221;<br />
        if ($(test-path ($OutPath + $OutFileName + &#8220;.xls&#8221;)))<br />
        {<br />
            del ($OutPath + $OutFileName + &#8220;.xls&#8221;)<br />
        }</p>
<p>        $sheetIndex = 0;<br />
        $oExcel = New-Object -COM Excel.Application<br />
        $oExcel.Visible = $false<br />
        $oBooks = $oExcel.Workbooks<br />
        $oCulture= [System.Globalization.CultureInfo]&#8220;en-US&#8221;<br />
        $oBook=$oBooks.psbase.gettype().InvokeMember(&#8220;Add&#8221;,[Reflection.BindingFlags]::InvokeMethod,$null,$oBooks,$null,$oCulture)<br />
        #$oSheet = $oBook.Worksheets.Item(1)</p>
<p>        $DataTable = $DataSet.Tables[0];<br />
        $nDr = $DataTable.Rows.Count + 1<br />
        $nDc = $DataTable.Columns.Count + 1</p>
<p>        # Create the object array<br />
        $rawData = new-object &#8216;object[,]&#8216; $nDr,$nDc  </p>
<p>        # Write the field names in the first row<br />
        for ($col = 0; $col -lt $DataTable.Columns.Count; $col++)<br />
        {<br />
            $rawData[0, $col] = $DataTable.Columns[$col].ColumnName;<br />
        }</p>
<p>        # Copy the dataset to the object array<br />
        for ($col = 0; $col -lt $DataTable.Columns.Count; $col++)<br />
        {<br />
            for ($row = 0; $row -lt $DataTable.Rows.Count; $row++)<br />
            {<br />
                $rawData[($row + 1), $col] = $DataTable.Rows[$row][$col];<br />
            }<br />
        }</p>
<p>        # Calculate the final column letter<br />
        $finalColLetter = &#8220;&#8221;;<br />
        $colCharset = &#8220;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#8221;;<br />
        $colCharsetLen = $colCharset.Length;<br />
        if ($DataTable.Columns.Count -gt $colCharsetLen)<br />
        {<br />
            $finalColLetter = $colCharset.Substring((($DataTable.Columns.Count &#8211; 1) / ($colCharsetLen &#8211; 1)), 1);<br />
        }<br />
        $finalColLetter += $colCharset.Substring(($DataTable.Columns.Count &#8211; 1) % $colCharsetLen, 1);</p>
<p>        ### Export it all to Excel #####<br />
        Write-Host &#8220;Writing to Excel&#8230;&#8221; -ForegroundColor &#8220;darkgreen&#8221;</p>
<p>        # Create a new Sheet<br />
        $excelSheet = $oBook.Worksheets.Item(1)</p>
<p>        #$excelSheet.name = $DataTable.TableName;               #TODO: Be nice to figure out how to make this work (not critical)</p>
<p>        # Create the entire range on the worksheet and dump the data into it<br />
        $excelRange = &#8220;A1:&#8221; + $finalColLetter + &#8220;&#8221; + ($DataTable.Rows.Count + 1)<br />
        $excelSheet.Range($excelRange).FormulaLocal = $rawData;</p>
<p>        # Mark the first row as BOLD                            #TODO: Be nice to figure out how to make this work (not critical)<br />
        #$excelSheet.Rows[1].Font.Bold = $True;<br />
        #$excelSheet.Cells.Item(1,1).Font.Bold = $True;</p>
<p>        # Save the Excel file and we&#8217;re done<br />
        Invoke $oBook SaveAs ($OutPath + $OutFileName + &#8220;.xls&#8221;) &gt; $null<br />
        Invoke $oBook Close 0 &gt;$null<br />
        $oExcel.Quit()<br />
    }<br />
}</p>
<p>Write-Host (&#8220;Complete&#8221;)</p>
]]></content:encoded>
	</item>
	<item>
		<title>Comment on QuerySQL.ps1 by Ram</title>
		<link>http://fwhagen.wordpress.com/querysqlps1/#comment-659</link>
		<dc:creator>Ram</dc:creator>
		<pubDate>Mon, 27 Apr 2009 15:18:43 +0000</pubDate>
		<guid isPermaLink="false">http://fwhagen.wordpress.com/?page_id=175#comment-659</guid>
		<description>Hi 

Your script is very very useful to me.

I am getting the error as below, Can you please send me the updated/fix script.

Exception calling &quot;InvokeMember&quot; with &quot;6&quot; argument(s): &quot;Exception has been thrown by the target of an
invocation.&quot;
At C:\RamMiscUtilities\PowerShellScripts\TSQLQuery_To_Excel.ps1:21 char:36
+ {  $m.PSBase.GetType().InvokeMember( &lt;&lt;&lt;&lt; $method, [Reflection.BindingFlags]::InvokeMethod, $null, $
m, $parameters, [System.Globalization.CultureInfo]&quot;en-US&quot;)  }

Thanks in advance</description>
		<content:encoded><![CDATA[<p>Hi </p>
<p>Your script is very very useful to me.</p>
<p>I am getting the error as below, Can you please send me the updated/fix script.</p>
<p>Exception calling &#8220;InvokeMember&#8221; with &#8220;6&#8243; argument(s): &#8220;Exception has been thrown by the target of an<br />
invocation.&#8221;<br />
At C:\RamMiscUtilities\PowerShellScripts\TSQLQuery_To_Excel.ps1:21 char:36<br />
+ {  $m.PSBase.GetType().InvokeMember( &lt;&lt;&lt;&lt; $method, [Reflection.BindingFlags]::InvokeMethod, $null, $<br />
m, $parameters, [System.Globalization.CultureInfo]&#8220;en-US&#8221;)  }</p>
<p>Thanks in advance</p>
]]></content:encoded>
	</item>
</channel>
</rss>
