<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Max Trinidad - The PowerShell Front</title>
	<atom:link href="http://www.maxtblog.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.maxtblog.com</link>
	<description>A little of everything about PowerShell!!!</description>
	<lastBuildDate>Tue, 21 Feb 2012 18:57:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>T-SQL &amp; PowerShell &#8211; Another way to Identify Database Snapshots</title>
		<link>http://www.maxtblog.com/2012/02/tsql-powershell-another-way-to-identify-database-snapshots/</link>
		<comments>http://www.maxtblog.com/2012/02/tsql-powershell-another-way-to-identify-database-snapshots/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 18:57:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1079</guid>
		<description><![CDATA[Just a quick blog on spotting your Database Snaphots. I just couldn&#8217;t believe that I&#8217;ve been missing creating SQL database snapshots but sometimes having so much work make you blind.  I&#8217;ve been using a lot Hyper-V Snapshot features and recently &#8230; <a href="http://www.maxtblog.com/2012/02/tsql-powershell-another-way-to-identify-database-snapshots/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Just a quick blog on spotting your Database Snaphots. I just couldn&#8217;t believe that I&#8217;ve been missing creating SQL database snapshots but sometimes having so much work make you blind.  I&#8217;ve been using a lot Hyper-V Snapshot features and recently (Thanks to <a href="http://sev17.com/" target="_blank">Chad Miller</a>) I got the chance to create and test a few.</p>
<p>So, first we need to create a new db snapshot of my AdventureWorks database using T-SQL Script:</p>
<pre class="brush: sql; title: ; notranslate">
CREATE DATABASE AdventureWorks_dbSnapShot_0001 ON
( NAME = AdventureWorks_Data, FILENAME =
'C:\Program Files\Microsoft SQL Server\MSSQL11.MSQLDENALICTP3\MSSQL\DATA\AdventureWorks_Data_0001.ss' )
AS SNAPSHOT OF AdventureWorks;
GO
</pre>
<p>Now, I go to SSMS and verify my new database snapshot exist by going into the &#8216;Object Explorer&#8217; and looking under &#8216;Database Shashots&#8217; folder.</p>
<h3>Using T-SQL</h3>
<p>If I use the following T-SQL command to list all my databases:</p>
<pre class="brush: sql; title: ; notranslate">
Select * from [sys].[sysdatabases]
</pre>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/ListwSysdatabases.png"><img class="aligncenter size-full wp-image-1093" title="ListwSysdatabases" src="http://www.maxtblog.com/wp-content/uploads/2012/02/ListwSysdatabases.png" alt="" width="953" height="379" /></a></p>
<p>I will get all of them listed including the snapshots. So, here&#8217;s another way to use T-SQL to identify all database snapshots. For that, I&#8217;m going to do a select and use from the Master db the view named &#8220;[sys].[databases]&#8220;:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT [name]
      ,[database_id]
      ,[source_database_id]
      ,[owner_sid]
      ,[create_date]
  FROM [master].[sys].[databases]
</pre>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/TSQL_IdentifyDBSnapshot.png"><img class="aligncenter size-full wp-image-1094" title="TSQL_IdentifyDBSnapshot" src="http://www.maxtblog.com/wp-content/uploads/2012/02/TSQL_IdentifyDBSnapshot.png" alt="" width="926" height="446" /></a></p>
<p>In this result, pay attention to the &#8220;[source_database_id]&#8221; column. Notice that this column is mostly &#8220;null&#8221; except when if it has a value. This value will match the &#8220;[Database_ID]&#8221; column. So, you can use this to identify database snapshots.</p>
<h3>Using PowerShell</h3>
<p>Now, let&#8217;s take a look on how to use PowerShell to identify database snapshots using SMO. In the following code I&#8217;m listing all databases but snapshots are also included.</p>
<pre class="brush: powershell; title: ; notranslate">
Import-Module SQLPS -DisableNameChecking
$MySQL = New-Object Microsoft.SqlServer.management.Smo.Server 'YourServername\InstanceName'
$MySQL.Databases | Select name
</pre>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/PS_DBSnapshots_listed.png"><img class="aligncenter size-full wp-image-1095" title="PS_DBSnapshots_listed" src="http://www.maxtblog.com/wp-content/uploads/2012/02/PS_DBSnapshots_listed.png" alt="" width="1130" height="485" /></a></p>
<p>So, in order to identify the database snapshot I need to look deeper into our .NET database object. Using the &#8220;<strong>Get-Member</strong>&#8221; command I can see what&#8217;s object are available.</p>
<pre class="brush: powershell; title: ; notranslate">
($MySQL.Databases) | Get-Member | Out-Gridview
</pre>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/PS_GetMember.png"><img class="aligncenter size-full wp-image-1096" title="PS_GetMember" src="http://www.maxtblog.com/wp-content/uploads/2012/02/PS_GetMember.png" alt="" width="790" height="756" /></a></p>
<p>Using the &#8220;<strong>Out-Gridview</strong>&#8221; command to view my results a separate popup window, I found two properties of interest:</p>
<ol>
<li>&#8216;<span style="color: #0000ff;"><em>IsDatabaseSnapshot</em></span>&#8216; &#8211; which show &#8220;<em>true</em>&#8221; us if is a snapshot.</li>
<li>&#8216;<span style="color: #0000ff;"><em>DatabaseSnapshotBaseName</em></span>&#8216; &#8211; which give us the origne of database name of the snapshot.</li>
</ol>
<p>So, now I can use the following PowerShell commands to show all my databases and identify the snapshots:</p>
<pre class="brush: powershell; title: ; notranslate">
$MySQL.Databases | `
   Select name, Owner, RecoveryModel, `
   IsDatabaseSnapshot, DatabaseSnapshotBaseName `
   FT -AutoSize;
</pre>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/PS_IdentifyDBSnapshot.png"><img class="aligncenter size-full wp-image-1097" title="PS_IdentifyDBSnapshot" src="http://www.maxtblog.com/wp-content/uploads/2012/02/PS_IdentifyDBSnapshot.png" alt="" width="1129" height="501" /></a></p>
<h3>Conclusion</h3>
<p>Using both T-SQL and PowerShell examples, now you have a startup point to spot and take some control over your database snapshots.</p>
<p>Happy PowerShelling!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/tsql-powershell-another-way-to-identify-database-snapshots/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>“Windows 8 PowerShell and Hyper-V 3.0 Preview” Slide deck and samples</title>
		<link>http://www.maxtblog.com/2012/02/%e2%80%9cwindows-8-powershell-and-hyper-v-3-0-preview%e2%80%9d-slide-deck-and-samples/</link>
		<comments>http://www.maxtblog.com/2012/02/%e2%80%9cwindows-8-powershell-and-hyper-v-3-0-preview%e2%80%9d-slide-deck-and-samples/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 21:01:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Windows 8]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1072</guid>
		<description><![CDATA[Last weekend at the &#8220;ITPro Camp Saturday&#8221; in Sarasota Forida was great event.  Thanks to everyone for participating, and taking the precious time on a Saturday to learn about new and current technologies.  It was a GREAT!! Here&#8217;s my “Windows &#8230; <a href="http://www.maxtblog.com/2012/02/%e2%80%9cwindows-8-powershell-and-hyper-v-3-0-preview%e2%80%9d-slide-deck-and-samples/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Last weekend at the &#8220;ITPro Camp Saturday&#8221; in Sarasota Forida was great event.  Thanks to everyone for participating, and taking the precious time on a Saturday to learn about new and current technologies.  It was a GREAT!!</p>
<p>Here&#8217;s my “Windows 8 PowerShell and Hyper-V 3.0 Preview”presentation and demo scripts use during the session:<br />
<iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" width="98px" height="120px" style="padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embed?cid=7FD7082276C66197&#038;resid=7FD7082276C66197%21361&#038;authkey=AElDC_taQUtAZwY"></iframe><br />
Please, don&#8217;t hesitate to contact me if you have any questions.</p>
<p>Thanks You!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/%e2%80%9cwindows-8-powershell-and-hyper-v-3-0-preview%e2%80%9d-slide-deck-and-samples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>It&#8217;s Just Random: PowerShell &#8211; Mistery of Redrum Solved!!</title>
		<link>http://www.maxtblog.com/2012/02/its-just-random-powershell-mistery-of-reddrum-solved/</link>
		<comments>http://www.maxtblog.com/2012/02/its-just-random-powershell-mistery-of-reddrum-solved/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 20:52:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1066</guid>
		<description><![CDATA[It&#8217;s Friday and I&#8217;m following Jeffery Hicks idea to have fun with PowerShell.  Well, here&#8217;s the mistery of Redrum solved one more time.  Some time ago, I remember seen some code for reversing a string of characters.  Well, here&#8217;s the &#8230; <a href="http://www.maxtblog.com/2012/02/its-just-random-powershell-mistery-of-reddrum-solved/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s Friday and I&#8217;m following Jeffery Hicks idea to have fun with PowerShell.  Well, here&#8217;s the mistery of Redrum solved one more time.  Some time ago, I remember seen some code for reversing a string of characters.  Well, here&#8217;s the one-liner I use to solve the puzzle:</p>
<pre class="brush: powershell; title: ; notranslate">
$str = &quot;Redrum&quot;;
[System.Array]::Reverse(([Array]$RevStr = $str.ToCharArray()));
foreach($chr in $RevStr){ $mistery += $chr }
$mistery;
</pre>
<p>That&#8217;s all for now&#8230;. Have fun with PowerShell!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/its-just-random-powershell-mistery-of-reddrum-solved/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QuickBlog: PowerShell Automating your Credentials</title>
		<link>http://www.maxtblog.com/2012/02/quickblogpowershell-automating-your-credentials/</link>
		<comments>http://www.maxtblog.com/2012/02/quickblogpowershell-automating-your-credentials/#comments</comments>
		<pubDate>Thu, 16 Feb 2012 20:25:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1060</guid>
		<description><![CDATA[Back in January, I did a quick blog about &#8220;Use PowerShell to submit SQLServicePack job to multiple Server&#8220;, in that script I have PowerShell to always prompt me for credentials.  But, after a while of typing over and over my &#8230; <a href="http://www.maxtblog.com/2012/02/quickblogpowershell-automating-your-credentials/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Back in January, I did a quick blog about &#8220;<a href="http://www.maxtblog.com/2012/01/quickblog-use-powershell-to-submit-sqlservicepack-job-to-multiple-server/" target="_blank">Use PowerShell to submit SQLServicePack job to multiple Server</a>&#8220;, in that script I have PowerShell to always prompt me for credentials.  But, after a while of typing over and over my password, I found to way to automate my credentials.   Yes!  By automating the credential step, I just could schedule the job, and have time to work with something else.</p>
<p>In this example, I&#8217;m passing my credential to the &#8220;<strong>Start-Transfer</strong>&#8221; command, so I can do my file download to my destination folder.  Here&#8217;s the code snippet to accomplish the automation:</p>
<pre class="brush: powershell; title: ; notranslate">
## - Automate to create your credential:
$MyUserName = &quot;Domain\Username&quot;;
$MyPassword =  ConvertTo-SecureString 'MyPwd001!' -asplaintext -force;
$MyCredentials = new-object `
-typename System.Management.Automation.PSCredential `
-argumentlist $MyUserName,$MyPassword;

## - Import the module and start the download process of one file:
Import-Module BitsTransfer;
Start-BitsTransfer `
-Credential $MyCredentials `
-Source 'http://YoufilesSite/Files/Demo01.zip' `
-Destination '\\YourServer\NetworkSharedFolder\Demo01.zip';
</pre>
<p>Ha!  I know what you&#8217;re think!  I&#8217;m hardcoding my password in the scripts.  So, our possible options would be: 1) you&#8217;re the only one running this script (don&#8217;t tell your boss),  2) You trust your Network security (humm!), or 3) find the way to encrypt the script so no one can guess the password.</p>
<p>There are products like SAPIEN&#8217;s PrimalScript and PrimalForms, that will let you create an executable out of your script, and then you can deploy it to your server.  But, then again, only you can make that decision.  I&#8217;m just showing that&#8217;s possible in case you need it.</p>
<p>Have fun with PowerShell!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/quickblogpowershell-automating-your-credentials/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;PowerShell Query for the T-SQL Developer&#8221; Slide deck and samples</title>
		<link>http://www.maxtblog.com/2012/02/powershell-query-for-the-t-sql-developer-slide-deck-and-samples/</link>
		<comments>http://www.maxtblog.com/2012/02/powershell-query-for-the-t-sql-developer-slide-deck-and-samples/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 20:53:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1052</guid>
		<description><![CDATA[Once again, Thanks! to Patrick LeBlanc for allowing me to present at today&#8217;s (02/15/2012) SQLLunch.com.  It was a Great! turned out with over 60 people attending.  To You All THANKS!!  (Recorded session will be available) Well, here&#8217;s my slide deck &#8230; <a href="http://www.maxtblog.com/2012/02/powershell-query-for-the-t-sql-developer-slide-deck-and-samples/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Once again, Thanks! to <em>Patrick LeBlanc</em> for allowing me to present at today&#8217;s (02/15/2012) <a title="SQL Lunch" href="http://www.SQLLunch.com">SQLLunch.com</a>.  It was a Great! turned out with over 60 people attending.  To You All THANKS!!  (<em>Recorded session will be available</em>)</p>
<p>Well, here&#8217;s my slide deck presentation, and the sample Demo scripts:<br />
<iframe title ="Preview" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" width="98px" height="120px" style="padding:0;background-color:#fcfcfc;" src="https://skydrive.live.com/embed?cid=7FD7082276C66197&#038;resid=7FD7082276C66197%21360&#038;authkey=AFNWGIx2WA2x8nc"></iframe></p>
<p>Also, I included the following comparison chart that help in your quest to adopt PowerShell.  This excel file is also included in the zipped file.  This is what I covered today except for &#8220;Sum&#8221;.</p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/TSQLvsPowerShellQueryChart.jpg"><img class="aligncenter size-full wp-image-1053" title="TSQLvsPowerShellQueryChart" src="http://www.maxtblog.com/wp-content/uploads/2012/02/TSQLvsPowerShellQueryChart.jpg" alt="" width="1051" height="560" /></a></p>
<p>I just realized that this topic could evolved to include a Part II where I could show more on: Group, Sum, Logic, and Functions.  So, later on, I will be posting more information the next &#8220;PowerShell Query for the T-SQL Developer&#8221; Part II.</p>
<p>Stay Tuned!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/powershell-query-for-the-t-sql-developer-slide-deck-and-samples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell Start-Demo now allows multi-lines one-liner</title>
		<link>http://www.maxtblog.com/2012/02/powershell-start-demo-now-allows-multi-lines-onliners/</link>
		<comments>http://www.maxtblog.com/2012/02/powershell-start-demo-now-allows-multi-lines-onliners/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 03:15:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1038</guid>
		<description><![CDATA[Well, I just couldn&#8217;t stop making necessary changes to this great presenter tool.  So, now Start-Demo will process your multi-lines one-liners which this couldn&#8217;t be done in the previous version. So, a good example of a one-liner having line continuation, &#8230; <a href="http://www.maxtblog.com/2012/02/powershell-start-demo-now-allows-multi-lines-onliners/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Well, I just couldn&#8217;t stop making necessary changes to this great presenter tool.  So, now <strong>Start-Demo</strong> will process your multi-lines one-liners which this couldn&#8217;t be done in the previous version.</p>
<p>So, a good example of a one-liner having line continuation, using the <span style="color: #0000ff;">Send-MailMessage</span> cmdlet, where we can use the &#8220;`&#8221; tick to separate the long command line with its parameters:</p>
<pre class="brush: powershell; title: ; notranslate">
## - Send email notification:
Send-MailMessage `
	-To 'Userto@Company1.com' `
	-From 'SenderFrom@Company2.com' `
	-Subject 'Test send from email' `
	-Body 'Check email!' `
	-SmtpServer 'Exchnage.Mailserver.com'
</pre>
<p>Here&#8217;s an example of how it look like using &#8220;<em><strong>Start-Demo</strong></em>&#8221; in StudioShell:</p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/StartDemoV20A_2-10-2012-10-11-35-PM1.png"><img class="aligncenter size-full wp-image-1048" title="StartDemoV20A_2-10-2012 10-11-35 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/StartDemoV20A_2-10-2012-10-11-35-PM1.png" alt="" width="869" height="606" /></a></p>
<p>And, here&#8217;s the updated Start-DemoSS.ps1 Version <del datetime="2012-02-13T01:50:03+00:00">2.0A</del> 2.0B (02/12/2012):<br />
<em>(apologies for the previous code posted here. It somehow I posted a bad code but I fix it tonight)</em></p>
<pre class="brush: powershell; title: ; notranslate">
###########################################################################
# Original Version: 1.1
# Updated to Version 2.0B, Maximo Trinidad, 02/12/2012
#--------------------------------------------------------------------------
# Comments:
# 1. Customized the foreground color to Cyan and backgroundColor to Black.
# 2. Created a Dump color to default to White.
# 3. Added to put back the default foreground and background colors.
# 4. Commented out the '(!) Suspense' option because Studio Shell can't
#    handle &quot;$host.NestedPrompt&quot;.
# 5. Modify the Help menu to acomodate changes.
# 6. Commented out all &quot;$Host.UI.RawUI.WindowTitle&quot;.
# 7. Replaced all &quot;[System.Console]::ReadLine()&quot; with &quot;Read-Host&quot;.
# 8. Added an end of results 'write-host&quot;-- Press Enter to continue --&quot;'
#    follow with a read-host similate a pause.
#
# Modifications:
# 02/10/2012 - Add section identify oneliners with continuation tick &quot;`&quot;.
# 02/10/2012 - Cleanup all unused V1 lines.
# 02/10/2012 - Make code to properly display continuation lines.
# 02/12/2012 - Fix info on Start time and duration.
# 02/12/2012 - Adjust execution message spacing.
#
###########################################################################

function Start-Demo
{
  param($file=&quot;.\demo.txt&quot;, [int]$command=0)

  ## - Saved previous default Host Colors:
  $defaultForegroundColor = $host.UI.RawUI.ForegroundColor;
  $defaultBackgroundColor = $host.UI.RawUI.BackgroundColor;

  ## - Customizing Host Colors:
  $host.UI.RawUI.ForegroundColor = &quot;Cyan&quot;;
  $host.UI.RawUI.BackgroundColor = &quot;Black&quot;;
  $CommentColor = &quot;Green&quot;
  $MetaCommandColor = &quot;Cyan&quot;
  $DumpColor = &quot;White&quot;
  $otherColor = &quot;Yellow&quot;
  Clear-Host

  ## - setting demo variables:
  $_Random = New-Object System.Random
  $_lines = @(Get-Content $file)
  $Global:starttime = [DateTime]::now
  $_PretendTyping = $true
  $_InterkeyPause = 100
  $Global:Duration = $null

  Write-Host -for $otherColor @&quot;
Start-Demo: $file - Start time: $starttime
Version 2.0B (02/12/2012)
NOTE: Start-Demo replaces the typing but runs the actual commands.
.

&quot;@
  $continuation = $false;

  # We use a FOR and an INDEX ($_i) instead of a FOREACH because
  # it is possible to start at a different location and/or jump
  # around in the order.
  for ($_i = $Command; $_i -lt $_lines.count; $_i++)
  {
    if ($_lines[$_i].StartsWith(&quot;#&quot;))
    {
        Write-Host -NoNewLine $(&quot;`n[$_i]PS&gt; &quot;)
        Write-Host -NoNewLine -Foreground $CommentColor $($($_Lines[$_i]) + &quot;  &quot;)
        continue
    }
	else
    {
        # Put the current command in the Window Title along with the demo duration
        $Global:Duration = [DateTime]::Now - $Global:StartTime
        Write-Host -NoNewLine $(&quot;`n[$_i]PS&gt; &quot;)
        $_SimulatedLine = $($_Lines[$_i]) + &quot;  &quot;

        for ($_j = 0; $_j -lt $_SimulatedLine.Length; $_j++)
        {
           Write-Host -NoNewLine $_SimulatedLine[$_j]

	           if ($_PretendTyping)
	           {
	               if ([System.Console]::KeyAvailable)
	               {
	                   $_PretendTyping = $False
	               }
	               else
	               {
	                   Start-Sleep -milliseconds $(10 + $_Random.Next($_InterkeyPause))
	               };
	           };

        } # For $_j
		$_PretendTyping = $true

    } # else

   if($_Lines[$_i] -notmatch '`')
   {
		#Write-Host &quot;Yes $($_Lines[$_i])&quot; -BackgroundColor white -ForegroundColor red;
		$_input = Read-Host;
   } #else { $continuation = $true}

    switch ($_input)
    {
################ HELP with DEMO
      &quot;?&quot;
        {
            Write-Host -ForeGroundColor Yellow @&quot;
--------------------------------------------------------------------------------
Start-Demo - Updated to Version 2.0B (12/12/2012)
Help Running Demo: $file
.
(#x) Goto Command #x    (b) Backup     (?) Help
(fx) Find cmds using X  (q) Quit       (s) Skip
(t)  Timecheck          (d) Dump demo  (px) Typing Pause Interval
.
NOTE 1: Any key cancels &quot;Pretend typing&quot; for that line.  Use  unless you
        want to run a one of these meta-commands.
.
NOTE 2: After cmd output, enter  to move to the next line in the demo.
        This avoids the audience getting distracted by the next command
        as you explain what happened with this command.
.
NOTE 3: The line to be run is displayed in the Window Title BEFORE it is typed.
        This lets you know what to explain as it is typing.
.
NOTE 4: Although this script is functional try not to &quot;Goto&quot; a continuation
        one-liner or it will go to a continues loop. I will correct this sympton
        soon. (02/12/2012)
---------------------------------------------------------------------------------
&quot;@;
			Write-Host &quot;-- Press Enter to continue --&quot; -BackgroundColor white `
				-ForegroundColor Magenta;
			Read-Host; cls;
            $_i -= 1
        }

      #################### PAUSE
      {$_.StartsWith(&quot;p&quot;)}
          {
               $_InterkeyPause = [int]$_.substring(1)
               $_i -= 1
          }

      ####################  Backup
      &quot;b&quot;
		{
	        if($_i -gt 0)
	        {
	            $_i --

	            while (($_i -gt 0) -and ($_lines[$($_i)].StartsWith(&quot;#&quot;)))
	            {
					$_i -= 1
	            }
	        }

	        $_i --
	        $_PretendTyping = $false
        }

      ####################  QUIT
      &quot;q&quot;
		{
			Write-Host -ForeGroundColor $OtherColor &quot;&quot;
			$host.UI.RawUI.ForegroundColor = $defaultForegroundColor;
			$host.UI.RawUI.BackgroundColor = $defaultBackgroundColor;
			cls;
			return
		}

		####################  SKIP
		&quot;s&quot;
		{
			Write-Host -ForeGroundColor $OtherColor &quot;&quot;
		}

		####################  DUMP the DEMO
		&quot;d&quot;
		{
			for ($_ni = 0; $_ni -lt $_lines.Count; $_ni++)
			{
				if ($_i -eq $_ni)
				{
					Write-Host -ForeGroundColor Yellow &quot;$(&quot;*&quot; * 25) &gt;Interrupted&lt; $(&quot;*&quot; * 25)&quot;
				}
				Write-Host -ForeGroundColor $DumpColor (&quot;[{0,2}] {1}&quot; -f $_ni, $_lines[$_ni])
			}
			$_i -= 1
			Write-Host &quot;-- Press Enter to continue --&quot; -BackgroundColor white `
			-ForegroundColor Magenta;
			Read-Host; cls;
		}

		####################  TIMECHECK
		&quot;t&quot;
		{
			$Global:Duration = [DateTime]::Now - $Global:StartTime
			Write-Host -ForeGroundColor $OtherColor $(&quot;Demo has run {0} Minutes and {1} Seconds`nYou are at line {2} of {3} &quot; `
				-f [int]$Global:Duration.TotalMinutes,[int]$Global:Duration.Seconds,$_i,($_lines.Count - 1))
			$_i -= 1
		}

		####################  FIND commands in Demo
		{$_.StartsWith(&quot;f&quot;)}
		{
			for ($_ni = 0; $_ni -lt $_lines.Count; $_ni++)
			{
				if ($_lines[$_ni] -match $_.SubString(1))
				{
				  Write-Host -ForeGroundColor $OtherColor (&quot;[{0,2}] {1}&quot; -f $_ni, $_lines[$_ni])
				}
			}
			$_i -= 1
		};

#####################  SUSPEND  # --&gt; not working in StudioShell: help (!)  Suspend (not working)
#
#      {$_.StartsWith(&quot;!&quot;)}
#          {
#             if ($_.Length -eq 1)
#             {
#                 Write-Host -ForeGroundColor $CommentColor &quot;&quot;
#                 function Prompt {&quot;[Demo Suspended]`nPS&gt;&quot;}
#                 $host.EnterNestedPrompt()
#             }else
#             {
#                 trap [System.Exception] {Write-Error $_;continue;}
#                 Invoke-Expression $(&quot;.{&quot; + $_.SubString(1) + &quot;}| out-host&quot;)
#             }
#             $_i -= 1
#          }
# --------------------------------------------------------------------------------

      ####################  GO TO
      {$_.StartsWith(&quot;#&quot;)}
          {
             $_i = [int]($_.SubString(1)) - 1
			 $Scriptline = $null;
			 $continuation = $false;
             continue
          }

      ####################  EXECUTE
      default
          {
             trap [System.Exception] {Write-Error $_;continue;};
			 ## - 02/10/2012-&gt; Commented out original line below
			 # Invoke-Expression $(&quot;.{&quot; + $_lines[$_i] + &quot;}| out-host&quot;)

			## - add section identify oneliners with continuation tick:
				[string] $Addline = $null;
				if($_lines[$_i] -match '`')
				{
					#Write-Host &quot; Found tick = $($_lines[$_i])&quot; -ForegroundColor yellow;
					$Addline = $_lines[$_i].replace('`','').tostring()
					$Scriptline += $Addline;
					$continuation = $true;
				}
				else
				{
					$Scriptline += $_lines[$_i].ToString();
					$continuation = $false;
				};
				if($continuation -eq $false)
				{
					## - Executive:
					Write-Host &quot; `r`n`t Executing Script...`r`n&quot; -ForegroundColor $otherColor;
					Invoke-Expression $(&quot;.{&quot; +$Scriptline + &quot;}| out-host&quot;)
				}
			## - --------------------------------------------------------------------
			 if($continuation -eq $false)
			 {
			 	Write-Host &quot;`r`n&quot;;
				Write-Host &quot;-- Press Enter to continue --&quot; -ForegroundColor Magenta `
					-BackgroundColor white;
				$Global:Duration = [DateTime]::Now - $Global:StartTime
				Read-Host;
				$Scriptline = $null;
			 };
          }
    } # Switch
  } # for
  ## Next three list to put backl the console default colors and do a clear screen:
  $host.UI.RawUI.ForegroundColor = $defaultForegroundColor;
  $host.UI.RawUI.BackgroundColor = $defaultBackgroundColor;
  cls;
  $Global:Duration = [DateTime]::Now - $Global:StartTime; Write-Host &quot;`r`n&quot;;
  Write-Host &quot;Start-Demo of $file completed:&quot; -ForegroundColor $otherColor;
  Write-Host -ForeGroundColor Yellow $(&quot;Total minutes/sec: {0}.{1}, Date: {2}&quot; `
  	-f [int]$Global:Duration.TotalMinutes, [int]$Global:Duration.Seconds, [DateTime]::now);
} # function
</pre>
<p>Have Fun with it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/powershell-start-demo-now-allows-multi-lines-onliners/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell Start-Demo makeover for StudioShell</title>
		<link>http://www.maxtblog.com/2012/02/powershell-start-demo-makeover-for-studioshell/</link>
		<comments>http://www.maxtblog.com/2012/02/powershell-start-demo-makeover-for-studioshell/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 15:39:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1027</guid>
		<description><![CDATA[I blogged about a nice Visual Studio addon &#8220;StudioShell&#8221; that fits very well with SSMS &#8220;SQL Server Management Studio 2012&#8220;, and I found this tool very useful for presenting.  But, when I try running the (long time) famous &#8220;Start-Demo&#8221; script, it &#8230; <a href="http://www.maxtblog.com/2012/02/powershell-start-demo-makeover-for-studioshell/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I blogged about a nice Visual Studio addon &#8220;<strong>StudioShell</strong>&#8221; that fits very well with <span style="color: #800080;">SSMS</span> &#8220;<span style="color: #800080;"><em>SQL Server Management Studio 2012</em></span>&#8220;, and I found this tool very useful for presenting.  But, when I try running the (long time) famous &#8220;<em><strong>Start-Demo</strong></em>&#8221; script, it gave me some errors.  Well, Thanks (again) to StudioShell developer Jim Christoper, he gave me a hint to why this was happenning.  Basically, this old &#8220;<em><strong>Start-Demo</strong></em>&#8221; uses some .NET calls which StudioShell can&#8217;t interpret because of the way it was develop, so it need a makeover.</p>
<p>So, I proceed to dive into the code and make some basic changes so it can work inside StudioShell.  Here&#8217;s how it looks running it from SSMS executing a demo script, and asking for (?) Help:</p>
<div id="attachment_1028" class="wp-caption aligncenter" style="width: 1046px"><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/StartDemo01_2-10-2012-10-11-07-AM.png"><img class="size-full wp-image-1028" title="StartDemo01_2-10-2012 10-11-07 AM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/StartDemo01_2-10-2012-10-11-07-AM.png" alt="" width="1036" height="892" /></a><p class="wp-caption-text">Start-Demo running in StudioShell</p></div>
<p>I change the color scheme, and added a message pause after displaying the result of the onliner.</p>
<div id="attachment_1029" class="wp-caption aligncenter" style="width: 922px"><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/Start-Demo02_2-10-2012-10-16-37-AM.png"><img class="size-full wp-image-1029" title="Start-Demo02_2-10-2012 10-16-37 AM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/Start-Demo02_2-10-2012-10-16-37-AM.png" alt="" width="912" height="380" /></a><p class="wp-caption-text">Showing some of the changes</p></div>
<p>Also, the new function will work on a normal PowerShell console, and at the end of the start-demo it will put back your default console colors.</p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/Start-Demo03_2-10-2012-10-35-57-AM.png"><img class="aligncenter size-full wp-image-1031" title="Start-Demo03_2-10-2012 10-35-57 AM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/Start-Demo03_2-10-2012-10-35-57-AM.png" alt="" width="910" height="368" /></a></p>
<p>Here&#8217;s the updated &#8220;<strong><em>Start-DemoSS.ps1</em></strong>&#8220;code:</p>
<pre class="brush: powershell; title: ; notranslate">
###########################################################################
# Original Version: 1.1
# Updated to Version 2.0, Maximo Trinidad, 02/09/2012
#--------------------------------------------------------------------------
# Comments:
# 1. Customized the foreground color to Cyan and backgroundColor to Black.
# 2. Created a Dump color to default to White.
# 3. Added to put back the default foreground and background colors.
# 4. Commented out the '(!) Suspense' option because Studio Shell can't
#    handle &quot;$host.NestedPrompt&quot;.
# 5. Modify the Help menu to acomodate changes.
# 6. Commented out all &quot;$Host.UI.RawUI.WindowTitle&quot;.
# 7. Replaced all &quot;[System.Console]::ReadLine()&quot; with &quot;Read-Host&quot;.
# 8. Added an end of results 'write-host&quot;-- Press Enter to continue --&quot;'
#    follow with a read-host similate a pause.
###########################################################################

function Start-Demo
{
  param($file=&quot;.\demo.txt&quot;, [int]$command=0)

  ## - Saved previous default Host Colors:
  $defaultForegroundColor = $host.UI.RawUI.ForegroundColor;
  $defaultBackgroundColor = $host.UI.RawUI.BackgroundColor;

  ## - Customizing Host Colors:
  $host.UI.RawUI.ForegroundColor = &quot;Cyan&quot;;
  $host.UI.RawUI.BackgroundColor = &quot;Black&quot;;
  $CommentColor = &quot;Green&quot;
  $MetaCommandColor = &quot;Cyan&quot;
  $DumpColor = &quot;White&quot;
  Clear-Host

  ## - setting demo variables:
  $_Random = New-Object System.Random
  $_lines = @(Get-Content $file)
  $_starttime = [DateTime]::now
  $_PretendTyping = $true
  $_InterkeyPause = 100
  Write-Host -for $CommentColor @&quot;
NOTE: Start-Demo replaces the typing but runs the actual commands.
.
&lt;Demo [$file] Started.  Type `&quot;?`&quot; for help&gt;
&quot;@

  # We use a FOR and an INDEX ($_i) instead of a FOREACH because
  # it is possible to start at a different location and/or jump
  # around in the order.
  for ($_i = $Command; $_i -lt $_lines.count; $_i++)
  {
    if ($_lines[$_i].StartsWith(&quot;#&quot;))
    {
        Write-Host -NoNewLine $(&quot;`n[$_i]PS&gt; &quot;)
        Write-Host -NoNewLine -Foreground $CommentColor $($($_Lines[$_i]) + &quot;  &quot;)
        continue
    }else
    {
        # Put the current command in the Window Title along with the demo duration
        $_Duration = [DateTime]::Now - $_StartTime
        #X  - $Host.UI.RawUI.WindowTitle = &quot;[{0}m, {1}s]    {2}&quot; -f [int]$_Duration.TotalMinutes, `
		#       [int]$_Duration.Seconds, $($_Lines[$_i])
        Write-Host -NoNewLine $(&quot;`n[$_i]PS&gt; &quot;)
        $_SimulatedLine = $($_Lines[$_i]) + &quot;  &quot;
        for ($_j = 0; $_j -lt $_SimulatedLine.Length; $_j++)
        {
           Write-Host -NoNewLine $_SimulatedLine[$_j]
           if ($_PretendTyping)
           {
               if ([System.Console]::KeyAvailable)
               {
                   $_PretendTyping = $False
               }
               else
               {
                   Start-Sleep -milliseconds $(10 + $_Random.Next($_InterkeyPause))
               }
           }
        } # For $_j
        $_PretendTyping = $true
    } # else

    #X - $_OldColor = $host.UI.RawUI.ForeGroundColor
    $host.UI.RawUI.ForeGroundColor = $MetaCommandColor
    #X - $_input=[System.Console]::ReadLine().TrimStart()
	$_input= Read-Host
    #X - $host.UI.RawUI.ForeGroundColor = $_OldColor

    switch ($_input)
    {
################ HELP with DEMO
      &quot;?&quot;
          {
            Write-Host -ForeGroundColor Yellow @&quot;
--------------------------------------------------------------------------------
Help Running Demo: $file
.
(#x) Goto Command #x    (b) Backup     (?) Help
(fx) Find cmds using X  (q) Quit       (s) Skip
(t)  Timecheck          (d) Dump demo  (px) Typing Pause Interval
.
NOTE 1: Any key cancels &quot;Pretend typing&quot; for that line.  Use &lt;SPACE&gt; unless you
        want to run a one of these meta-commands.
.
NOTE 2: After cmd output, enter &lt;CR&gt; to move to the next line in the demo.
        This avoids the audience getting distracted by the next command
        as you explain what happened with this command.
.
NOTE 3: The line to be run is displayed in the Window Title BEFORE it is typed.
        This lets you know what to explain as it is typing.
---------------------------------------------------------------------------------
&quot;@;
			Write-Host &quot;-- Press Enter to continue --&quot; -BackgroundColor white `
				-ForegroundColor Magenta;
			Read-Host; cls;
            $_i -= 1
          }

      #################### PAUSE
      {$_.StartsWith(&quot;p&quot;)}
          {
               $_InterkeyPause = [int]$_.substring(1)
               $_i -= 1
          }

      ####################  Backup
      &quot;b&quot; {
                if($_i -gt 0)
                {
                    $_i --

                    while (($_i -gt 0) -and ($_lines[$($_i)].StartsWith(&quot;#&quot;)))
                    {   $_i -= 1
                    }
                }

                $_i --
                $_PretendTyping = $false
          }

      ####################  QUIT
      &quot;q&quot;
          {
            Write-Host -ForeGroundColor $CommentColor &quot;&lt;Quit demo&gt;&quot;
			  $host.UI.RawUI.ForegroundColor = $defaultForegroundColor;
			  $host.UI.RawUI.BackgroundColor = $defaultBackgroundColor;
			  cls;
            return
          }

      ####################  SKIP
      &quot;s&quot;
          {
            Write-Host -ForeGroundColor $CommentColor &quot;&lt;Skipping Cmd&gt;&quot;
          }

      ####################  DUMP the DEMO
      &quot;d&quot;
         {
            for ($_ni = 0; $_ni -lt $_lines.Count; $_ni++)
            {
               if ($_i -eq $_ni)
               {   Write-Host -ForeGroundColor Yellow &quot;$(&quot;*&quot; * 25) &gt;Interrupted&lt; $(&quot;*&quot; * 25)&quot;
               }
               Write-Host -ForeGroundColor $DumpColor (&quot;[{0,2}] {1}&quot; -f $_ni, $_lines[$_ni])
            }
            $_i -= 1
			Write-Host &quot;-- Press Enter to continue --&quot; -BackgroundColor white `
				-ForegroundColor Magenta;
			Read-Host; cls;
          }

      ####################  TIMECHECK
      &quot;t&quot;
          {
             $_Duration = [DateTime]::Now - $_StartTime
             Write-Host -ForeGroundColor $CommentColor $(
                &quot;Demo has run {0} Minutes and {1} Seconds`nYou are at line {2} of {3} &quot; -f
                    [int]$_Duration.TotalMinutes,
                    [int]$_Duration.Seconds,
                    $_i,
                    ($_lines.Count - 1)
             )
             $_i -= 1
          }

      ####################  FIND commands in Demo
      {$_.StartsWith(&quot;f&quot;)}
          {
            for ($_ni = 0; $_ni -lt $_lines.Count; $_ni++)
            {
               if ($_lines[$_ni] -match $_.SubString(1))
               {
                  Write-Host -ForeGroundColor $CommentColor (&quot;[{0,2}] {1}&quot; -f $_ni, $_lines[$_ni])
               }
            }
            $_i -= 1
          }

#      ####################  SUSPEND
# --&gt; not working in StudioShell: help (!)  Suspend (not working)
#
#      {$_.StartsWith(&quot;!&quot;)}
#          {
#             if ($_.Length -eq 1)
#             {
#                 Write-Host -ForeGroundColor $CommentColor &quot;&lt;Suspended demo - type 'Exit' to resume&gt;&quot;
#                 function Prompt {&quot;[Demo Suspended]`nPS&gt;&quot;}
#                 $host.EnterNestedPrompt()
#             }else
#             {
#                 trap [System.Exception] {Write-Error $_;continue;}
#                 Invoke-Expression $(&quot;.{&quot; + $_.SubString(1) + &quot;}| out-host&quot;)
#             }
#             $_i -= 1
#          }

      ####################  GO TO
      {$_.StartsWith(&quot;#&quot;)}
          {
             $_i = [int]($_.SubString(1)) - 1
             continue
          }

      ####################  EXECUTE
      default
          {
             trap [System.Exception] {Write-Error $_;continue;}
             Invoke-Expression $(&quot;.{&quot; + $_lines[$_i] + &quot;}| out-host&quot;)
			 Write-Host &quot;-- Press Enter to continue --&quot; -BackgroundColor white -ForegroundColor Magenta;
             $_Duration = [DateTime]::Now - $_StartTime
             #X - $Host.UI.RawUI.WindowTitle = &quot;[{0}m, {1}s]    {2}&quot; -f [int]$_Duration.TotalMinutes, `
			 #      [int]$_Duration.Seconds, $($_Lines[$_i])
             #X - [System.Console]::ReadLine()
			 Read-Host;
          }
    } # Switch
  } # for
  ## Next three list to put backl the console default colors and do a clear screen:
  $host.UI.RawUI.ForegroundColor = $defaultForegroundColor;
  $host.UI.RawUI.BackgroundColor = $defaultBackgroundColor;
  cls;
  $_Duration = [DateTime]::Now - $_StartTime
  Write-Host -ForeGroundColor $CommentColor $(&quot;&lt;Demo Complete {0} Minutes and {1} Seconds&gt;&quot; `
  	-f [int]$_Duration.TotalMinutes, [int]$_Duration.Seconds)
  Write-Host -ForeGroundColor $CommentColor $([DateTime]::now)
} # function
</pre>
<p>Please, notice I named the script as &#8220;<em><strong>Start-DemoSS.ps1</strong></em>&#8221; meaning for StudioShell, still the function will be loaded as &#8220;<em><strong>Start-Demo</strong></em>&#8220;.</p>
<p>Usage Syntax &#8211; To load from script folder location:</p>
<p><span style="color: #0000ff;">.  .\Start-DemoSS.ps1</span></p>
<p>Usage Syntax &#8211; To excute a Demo.txt file:</p>
<p><span style="color: #0000ff;">Start-Demo .\MyDemoScript.txt</span></p>
<p>What&#8217;s inside the demo file? This is a text file containing PowerShell <span style="color: #0000ff;">oneliners</span>, and &#8220;<span style="color: #008080;">#</span>&#8221; comment lines.</p>
<p>In case you want to try StudioShell: <a href="http://studioshell.codeplex.com/">http://studioshell.codeplex.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/powershell-start-demo-makeover-for-studioshell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Codeplex StudioShell in SSMS 2012 &#8211; Try it!!</title>
		<link>http://www.maxtblog.com/2012/02/codeplex-studioshell-in-ssms-2012-try-it/</link>
		<comments>http://www.maxtblog.com/2012/02/codeplex-studioshell-in-ssms-2012-try-it/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 22:02:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1018</guid>
		<description><![CDATA[If you haven&#8217;t yet try it, go ahead download and install this Visual Studio Extension to your SQL Server Management Studio 2012.  This tool will integrate a PowerShell host into your SSMS which you will love for presentations and quick &#8230; <a href="http://www.maxtblog.com/2012/02/codeplex-studioshell-in-ssms-2012-try-it/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t yet try it, go ahead download and install this Visual Studio Extension to your SQL Server Management Studio 2012.  This tool will integrate a PowerShell host into your SSMS which you will love for presentations and quick scripts developement from one envirment.  But Yes! this a just a simple host and you&#8217;ll find it useful for learning SQL PowerShell.</p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/StudioShellinSSMS2012_2-9-2012-3-53-19-PM.png"><img class="aligncenter size-full wp-image-1019" title="StudioShellinSSMS2012_2-9-2012 3-53-19 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/StudioShellinSSMS2012_2-9-2012-3-53-19-PM.png" alt="" width="1258" height="923" /></a></p>
<p>I will be presenting with this tool in my upcoming webinar with Patrick DeBlanc <a title="SQL Lunch site" href="http://www.sqllunch.com/" target="_blank">SQLLunch</a> next week on February 15th &#8220;<strong><em>PowerShell Query for the T-SQL Developer</em></strong>&#8221; at 11:30am CST / 12:30pm EST.</p>
<p>To download StudioShell, here&#8217;s the link: <a href="http://studioshell.codeplex.com/">http://studioshell.codeplex.com/</a></p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/StudioShellWeb_2-9-2012-3-58-43-PM.png"><img class="aligncenter size-full wp-image-1020" title="StudioShellWeb_2-9-2012 3-58-43 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/StudioShellWeb_2-9-2012-3-58-43-PM.png" alt="" width="1044" height="671" /></a></p>
<p>After you install this application, open SSMS,  from the top menu click on &#8220;<strong>View</strong>&#8220;, and select &#8220;<strong>StudioShell</strong>&#8220;.  Then, you can place this pane anywhere inside your SSMS application.  You can copy/paste t-sql code put remember to import the SQLPS module to have access to your SQL PowerShell commands.</p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/ExecutingTSQL_line_2-9-2012-4-08-44-PM.png"><img class="aligncenter size-full wp-image-1021" title="ExecutingTSQL_line_2-9-2012 4-08-44 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/ExecutingTSQL_line_2-9-2012-4-08-44-PM.png" alt="" width="1251" height="924" /></a></p>
<p>A word of advice! if you venture to go, under <strong>&#8216;Tools | Options</strong>&#8220;, to change the &#8220;<strong>Console Choice</strong>&#8221; to be &#8220;<em>Old School</em>&#8220;, you will crash your SSMS application when you exit the StudioShell console.  So, <span style="color: #993300;">DON&#8217;T make any changes to your Console Choice options, or you&#8217;ll end up loose all your work</span>.</p>
<p><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/StudioShellDont_2-9-2012-4-56-49-PM1.png"><img class="aligncenter size-full wp-image-1024" title="StudioShellDont_2-9-2012 4-56-49 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/02/StudioShellDont_2-9-2012-4-56-49-PM1.png" alt="" width="1004" height="646" /></a></p>
<p>I&#8217;m a believer of Tools that can help you be productive, and this one caught my attention.  Please, try it!</p>
<p>Good Job JimChristopher (StudioShell Developer)/@beefarino !!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/codeplex-studioshell-in-ssms-2012-try-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell quick list of SQL Users with SysAdmin Role</title>
		<link>http://www.maxtblog.com/2012/02/powershell-quick-list-of-sql-users-with-sysadmin-roles/</link>
		<comments>http://www.maxtblog.com/2012/02/powershell-quick-list-of-sql-users-with-sysadmin-roles/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 17:18:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Office]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=1004</guid>
		<description><![CDATA[Here&#8217;s a quick way to start getting a list of SQL Server users having &#8220;SysAdmin&#8221; Role.  Basically, I&#8217;m using SQLPS module (now available with SQL Server 2012) which loads all the SMO needed to help you script against your SQL &#8230; <a href="http://www.maxtblog.com/2012/02/powershell-quick-list-of-sql-users-with-sysadmin-roles/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a quick way to start getting a list of SQL Server users having &#8220;SysAdmin&#8221; Role.  Basically, I&#8217;m using SQLPS module (now available with SQL Server 2012) which loads all the SMO needed to help you script against your SQL engine.</p>
<p>This script does the following:</p>
<ol>
<li>Import the SQLPS Module.</li>
<li>Connect to a SQL Server Instance.</li>
<li>Get the SQL Logins information.</li>
<li>Search for SQL users with &#8220;SysAdmin&#8221; Role, and builds a customized information in a PSObject.</li>
<li>Export the information to a CSV file.</li>
<li>Open the CSV file, which by default could open an Excel application(if installed on machine).</li>
</ol>
<p>Here&#8217;s the code:</p>
<pre class="brush: powershell; title: ; notranslate">
Import-Module SQLPS -disablenamechecking

$SQLSvr = &quot;SQLServername\Instancename&quot;;
$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
$SQLLogins = $MySQL.Logins;

$SysAdmins = $null;
$SysAdmins = foreach($SQLUser in $SQLLogins)
{
	foreach($role in $SQLUser.ListMembers())
	{
		if($role -match 'sysadmin')
		{
		    Write-Host &quot;SysAdmins found: $($SQLUser.Name)&quot; -ForegroundColor Yellow;
		    $SQLUser | Select-Object `
		     @{label = &quot;SQLServer&quot;; Expression = {$SQLSvr}}, `
		     @{label = &quot;CurrentDate&quot;; Expression = {(Get-Date).ToString(&quot;yyyy-MM-dd&quot;)}}, `
		     Name, LoginType, CreateDate, DateLastModified;
		};
	};
};

$SysAdmins | Export-Csv -Path 'C:\temp\SQLSysAdminList.csv' -Force -NoTypeInformation;
ii 'C:\temp\SQLSysAdminList.csv';
</pre>
<div id="attachment_1006" class="wp-caption aligncenter" style="width: 1042px"><a href="http://www.maxtblog.com/wp-content/uploads/2012/02/ListSysAdminRoles.jpg"><img class="size-full wp-image-1006" title="ListSysAdminRoles" src="http://www.maxtblog.com/wp-content/uploads/2012/02/ListSysAdminRoles.jpg" alt="" width="1032" height="543" /></a><p class="wp-caption-text">Sample CSV output</p></div>
<p>Eventually, you could make changes to this scritp to be capable to access a list of SQL Servers and build your custom report.</p>
<p>Bonus:</p>
<p>To add the functionallity to connect to multiple servers, we can add a list of Servers and then using the &#8220;Foreach&#8221; statement to loop through the list, and with little changes to the previous code.</p>
<p>Here&#8217;s how it will look with just adding a few more line of code:</p>
<pre class="brush: powershell; title: ; notranslate">
## - Loads SQL Powerhell SMO and commands:
Import-Module SQLPS -disablenamechecking

## - BUild list of Servers manually (this builds an array list):
$SQLServers = &quot;Server01&quot;,&quot;Server01\InstanceNameA&quot;,&quot;Server03&quot;;
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{

	## - Add Code block:
	$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
	$SQLLogins = $MySQL.Logins;

	$SysAdmins += foreach($SQLUser in $SQLLogins)
	{
		foreach($role in $SQLUser.ListMembers())
		{
			if($role -match 'sysadmin')
			{
			    Write-Host &quot;SysAdmins found: $($SQLUser.Name)&quot; -ForegroundColor Yellow;
			    $SQLUser | Select-Object `
			     @{label = &quot;SQLServer&quot;; Expression = {$SQLSvr}}, `
			     @{label = &quot;CurrentDate&quot;; Expression = {(Get-Date).ToString(&quot;yyyy-MM-dd&quot;)}}, `
			     Name, LoginType, CreateDate, DateLastModified;
			};
		};
	};
	## - End of Code block

}

## - BUild and open report:
$SysAdmins | Export-Csv -Path 'C:\temp\SQLSysAdminList.csv' -Force -NoTypeInformation;
ii 'C:\temp\SQLSysAdminList.csv';
</pre>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/02/powershell-quick-list-of-sql-users-with-sysadmin-roles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QuickBlog &#8211; Use PowerShell to submit SQLServicePack job to multiple Server</title>
		<link>http://www.maxtblog.com/2012/01/quickblog-use-powershell-to-submit-sqlservicepack-job-to-multiple-server/</link>
		<comments>http://www.maxtblog.com/2012/01/quickblog-use-powershell-to-submit-sqlservicepack-job-to-multiple-server/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 21:53:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Windows 8]]></category>

		<guid isPermaLink="false">http://www.maxtblog.com/?p=991</guid>
		<description><![CDATA[This was an interesting discussion in the LinkedIn &#8220;How to Install SQL Service Pack by PowerShell?&#8221;.  I got the chance to create and test this one out. I scratched the previous script I posted trying to show probe a concept, and &#8230; <a href="http://www.maxtblog.com/2012/01/quickblog-use-powershell-to-submit-sqlservicepack-job-to-multiple-server/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This was an interesting discussion in the LinkedIn &#8220;How to Install SQL Service Pack by PowerShell?&#8221;.  I got the chance to create and test this one out. I scratched the previous script I posted trying to show probe a concept, and ended up creating a new smaller script. Funny!! I created a smaller script!</p>
<p>Well, I just confirmed that&#8217;s possible to submit an unattended SQL ServicePack installer as a job using PowerShell Remoting. I&#8217;m using my Hyper-V Virtual Domain I ran the script from a Windows 7 VM and submitted one job to two servers. I could see the the jobs processing on the server Task Manager.</p>
<p>But, it was tedious? If you&#8217;re a newbie maybe it&#8217;s a little over your head but not impossible. That&#8217;s the intention of PowerShell Remoting, to be able to do these things like this, and I&#8217;m just scratching the surface. Please, Take advantage of these features in PS V2.0, and more enhancements has been done in PS v3.0 with the inclusion of Workflows.</p>
<p>Still, you will need to use PowerShell &#8220;<span style="color: #0000ff;"><strong>Enable-PSRemoting</strong></span> <em><strong>-force</strong></em>&#8221; in all the servers. I know, this may be an issue but you need to configure it on all the servers in order to take advantage of PowerShell Remoting. Now, I&#8217;m creating session on each computer so I can run as jobs, and your credential is Important to be included. All this is done from your desktop, no more running to the server room.</p>
<p>This time I did test the new script using Sessions in PS Remoting:</p>
<pre class="brush: powershell; title: ; notranslate">
## - Get your credential information top connect to servers:
$getCred = Get-Credential 'Domain99\UserName99'
$servers = &quot;Server1&quot;,&quot;Server2&quot;;
$Jobsession = New-PSSession -Computername $servers -Credential $getCred;

## - display the sessions:
$Jobsession

## - Submit jobs to background process on selected servers:
Invoke-Command -Session $Jobsession -AsJob -JobName 'TestBackgroundInstall' `
-ScriptBlock {
new-psdrive -name SQLInstallDrive -psprovider FileSystem -root \\WIN8Server1\install;
cd SQLInstallDrive:;
&amp; ./SQLServer2008R2SP1-KB2528583-x64-ENU.exe /allinstances;
};

## To Display jobs:
get-job

## - To Close PS Sessions and remove variabler:
Remove-PSSession $Jobsession
Remove-Variable Jobsession
</pre>
<p>In the &#8220;<strong>Invoke-Command</strong>&#8220;, the <strong><em>&#8220;-ScriptBlock&#8221;</em></strong> parameter will hold the code you&#8217;re executing on the server as a background job.  Inside the &#8216;-scriptblock { .. }&#8217; parameter, I&#8217;m executing three commands:</p>
<p>1. Creating the PSdrive to the &#8220;Install&#8221; shared folder.<br />
2. Changing directory (this one could be optional).<br />
3. Finally, run the SQLServer2008R2SP1-KB2528583-x64-ENU.exe SQL Service Pack,</p>
<p>This way you&#8217;re not holding the PowerShell Console hostage. You could even make this script more robust. You could add the parameter <em><strong>&#8220;-ThrottleLimit&#8221;</strong></em> to specify the max number of concurrent connections, to minimize the network traffic. This is just a start, this code can be improve a lot.</p>
<div id="attachment_993" class="wp-caption aligncenter" style="width: 1436px"><a href="http://www.maxtblog.com/wp-content/uploads/2012/01/Ask_Cred_1-25-2012-3-11-59-PM1.png"><img class="size-full wp-image-993" title="Ask_Cred_1-25-2012 3-11-59 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/01/Ask_Cred_1-25-2012-3-11-59-PM1.png" alt="" width="1426" height="990" /></a><p class="wp-caption-text">You&#39;ll need to supply your Windows Credentials</p></div>
<div id="attachment_995" class="wp-caption aligncenter" style="width: 1349px"><a href="http://www.maxtblog.com/wp-content/uploads/2012/01/SubmitBackgroundJob_1-25-2012-3-15-56-PM1.png"><img class="size-full wp-image-995" title="SubmitBackgroundJob_1-25-2012 3-15-56 PM" src="http://www.maxtblog.com/wp-content/uploads/2012/01/SubmitBackgroundJob_1-25-2012-3-15-56-PM1.png" alt="" width="1339" height="749" /></a><p class="wp-caption-text">Submitting the job from Windows</p></div>
<div class="mceTemp mceIEcenter"> For more information about PowerShell Remoting, type at the PowerShell Prompt:<br />
<span style="color: #0000ff;"><strong>get-help</strong></span> <strong>About_Remoting</strong> -full<br />
<strong><span style="color: #0000ff;">get-help</span></strong> <strong>Invoke-Command</strong> -full</div>
<p>Check out the TechNet Tip link on PS Remoting:<br />
<a href="http://technet.microsoft.com/en-us/magazine/ff700227.aspx">http://technet.microsoft.com/en-us/magazine/ff700227.aspx</a></p>
<p>Added: Please, check this TechEd 2011 video of my college Don Jones talking about &#8220;Windows PowerShell Remoting: Definitely NOT Just for Servers&#8221;:<br />
<a href="http://www.linkedin.com/redirect?url=http%3A%2F%2Fchannel9%2Emsdn%2Ecom%2FEvents%2FTechEd%2FNorthAmerica%2F2011%2FWCL321&amp;urlhash=V-Ec&amp;_t=tracking_disc" rel="nofollow" target="blank">http://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/WCL321</a></p>
<p>Of course, there are products out there to help manage/automate your Microsoft security, and service packs.  But you will still need to invest time configuring the application.</p>
<p>Well!! This was a good one.<br />
 <img src='http://www.maxtblog.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.maxtblog.com/2012/01/quickblog-use-powershell-to-submit-sqlservicepack-job-to-multiple-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

