PowerShell and BASH setup walkthru

Yes! I finally got the latest Windows 10 Build 14328 which includes BASH Ubuntu Linux subsystem.  I took me few days since my organization did a Windows 7 upgrade to Windows 10 Version 1511. Then, thru Windows Insider, getting the latest version with Bash.

WindowsBash_00

If it worth knowing that in order to get Bash, it’s a feature you need to installed it first. The following is the series of steps I use to enabled and install Bash on my desktop. And, after enabling Bash, I started using it under the PowerShell Console.

Set bash Feature On

Go to Control Panel, under Programs click “Uninstall a program” then click on “Turn Windows features on or off“.  Under the “Windows Features” popup windows Look and Enable “Windows Subsystem for Linux (beta)”. Click OK to accept changes.

WindowsBash_01

Using PowerShell Console and Set Developer Mode

Open PowerShell Console but make sure you already have set the “Execution Policy” to at least “RemoteSigned“.  Type and execute “bash” but it won’t work because you need to have your Windows 10 set to Developer Mode.

WindowsBash_02

The following screen show how to go thru the “Setting” panel to enable Windows Developer Mode.

WindowsBash_03 WindowsBash_04 WindowsBash_05 WindowsBash_06

Ready for Bash

At the PowerShell prompt type “bash” and press enter. This will ask to enter “y” to initiate the installation of Ubuntu on Windows.

WindowsBash_07 WindowsBash_09

After the installation is completed the next step is to create a User-ID and Password.

WindowsBash_10

Now, you can start using Linux within PowerShell.

WindowsBash_11

To get back to PowerShell just type “exit“. How cool is that!!

WindowsBash_12

 

PowerShell at the Orlando Code Camp 2016

Orlandocc

Orlando Code Camp 2016, Saturday April 2..

I had the pleasure to once again be a speaker at this activity since (I think) I started speaking in 2008. I have to say this is one of my favorite event I love to attend.

20160402_085402

I appreciate all 22 attendees that came to my session “The Essentials of Tackling PowerShell Basic Functions”.  Here’s where I show everyone how they can evolve their scripting skills. Showing how from a single cmdlet evolves to script and the a possible function.  But, still so much to learn about PowerShell and leting them know the “Get-Help” cmdlet is a good start.

20160402_100228

At the same time, I showcase Sapien Technologies “PowerShell Studio 2016” and gave them a taste of a useful Windows application built in PowerShell.

PowershellStudio

PowershellStudio2

Here’s the link to both the presentation and sample scripts:
https://onedrive.live.com/redir?resid=545C43857DEBA04A!588&authkey=!AKtBq5rmFCvsbgg&ithint=file%2czip

And, we got a winner in the raffle at the end of my presentation.

20160402_105606

Please check out my “The Essentials” series at Idera’s Geek Sync: (make sure to select “Webcast”)
https://www.idera.com/resourcecentral/resourceresults?rt=webcast&s=sm_twitter_spwc

 

Windows Management Framework 5.0 RTM is HERE!

Finally! The Windows Management Framework version 5.0 RTM is available for download for all down level Operating systems: Windows 7, Windows 8.1, Windows Servers 2008 R2, Windows Server 2012, and Windows Servers 2012 R2.

WMF50_01_12-18-2015 10-42-32 PM

Download link here: https://www.microsoft.com/en-us/download/details.aspx?id=50395

WMF50_02_12-18-2015 10-42-32 PM

You’ll notice that there are no download files for Windows 7 SP1 x64 and Windows 8.1 x64.  In order the install either of these you can use the following:

1. For Windows 7 SP1 x64 – Download and install: W2K8R2-KB3094176-x64.msu

2. For Windows 8.1 x64 – Download and install: W2K12-KB3094175-x64.msu

Check out the list of new and updated features:  (extracted from the “Detail” section)

  • Develop with classes in Windows PowerShell
  • Just Enough Administration (JEA)
  • Extract and parse structured object out of string content
  • More control in Windows PowerShell Remote Debugging
  • PowerShell Information Stream
  • New and updated cmdlets based on community feedback
  • Generate Windows PowerShell cmdlets based on an OData endpoint with ODataUtils
  • Manage .ZIP archives through new cmdlets
  • Interact with symbolic links using improved Item cmdlets
  • DSC authoring improvements in Windows PowerShell ISE
  • 32-bit support for the configuration keyword in DSC
  • Audit Windows PowerShell usage by transcription and logging
  • Configure DSC’s Local Configuration Manager with the meta-configuration attribute
  • Configure piece by piece with partial configurations in DSC
  • Manage with cross-computer dependencies in DSC
  • More control over configurations in DSC
  • Find more detail about configuration status in DSC
  • Support for -? during DSC configuration compilation
  • Support for DSC RunAsCredential
  • Rich information for DSC LCM State
  • Side-by-Side installation of DSC Resources and PowerShell Modules
  • PSDesiredStateConfiguration Module version updated to 1.1
  • Report configuration status from DSC to a central location
  • Discover and install software with PackageManagement
  • Discover PowerShell Modules, PowerShell Scripts and DSC resources with PowerShellGet
  • Network Switch management with Windows PowerShell
  • Software Inventory Logging (SIL)

Go ahead, download, and start using PowerShell version 5.0.

WMF50_03_12-18-2015 10-42-32 PM

SAPIEN PowerShell Studio 2015 is PowerShell v5.0 ready: https://www.sapien.com/software/powershell_studio

SAPIEN_WMF50_02_12-18-2015 10-42-32 PM

FLPSUG – Max Trinidad on “PowerShell Deep Dive to Excel” video

Back in October 2014, I presented and recorded on my topic about working with Excel and PowerShell. I thought this video was lost but I founded it on a backup drive.  Well its loaded with good samples using my favorite tool: SAPIEN’s PowerShell Studio. These tools are an essential for building .NET scripting and applications with PowerShell.

Check out the video at:

FLPSUG – Tim Warner on “Mastering Regular Expression in Windows PowerShell” video

The week before Thanksgiving we got Mr. Tim Warner presenting for our FLPSUG group on the topic of working with “Regular Expressions” in PowerShell.  It was a GREAT presentation loaded with information.

We recorded the video, and he provided his contact information and a link for this demo scripts:
1. Contact Tim Warner at:  timothywarner316@gmail.com
2. Demo scripts: http://timwarnertech.com/flpsug.zip

Check out the video at:

Azure PowerShell Preview 1.0 is here

Welcome to PowerShell Azure Resource Manager (RM)!

Microsoft has introduce and made available Azure PowerShell Preview 1.0.  Please read all about it in the following Azure Blog site:

Also, feel free to search for it at usign the following link:

Some Interesting links 

Well, within the search there are more interesting blog articles to start doing some PowerShell scripting:

How to install and configure Azure PowerShell: https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/

Using Azure PowerShell with Azure Resource Manager: https://azure.microsoft.com/en-us/documentation/articles/powershell-azure-resource-manager/

Manage Azure SQL Database with PowerShell: https://azure.microsoft.com/en-us/documentation/articles/sql-database-command-line-tools/

Integrating SQL AlwaysOn with Azure Site Recovery: https://azure.microsoft.com/en-gb/blog/integrating-sql-alwayson-with-azure-site-recovery/

Get it at PowerShell Gallery

Now, my question here is, did you found Azure PowerShell 1.0 Preview? Probably not, but in fact, it’s AzureRM 1.0.1 to be installed. Although, I did found Azure version 0.9.11 and, Yes! I did download that one just in case.

To download these new bits from the PowerShell Gallery, check out the “Get Started with the PowerShell Gallery” link: http://www.powershellgallery.com/pages/GettingStarted

AzureRM_01_10-16-2015

Search for both “Azure” and AzureRM”.

AzureRM_02_10-16-2015

AzureRM_03_10-16-2015

During my quest to download Azure PowerShell 1.0, I realized that its AzureRM the one I need to download using: “Install-Module AzureRM” followed by “Install-AzureRM -force“.

AzureRM_04_10-16-2015

To start using the AzureRM Cmdlets, just run the “Import-AzureRM” command.

AzureRM_07_10-16-2015

Now, we are ready to play with Azure Resource Manager and Azure SQL databases.   There’s a total of 653 *AzureRM* cmdlets.

AzureRM_08_10-16-2015

AzureRM_09_10-16-2015

Run the following command to list all *AzureRM* commands:

Import-AzureRM; Get-Command *AzureRM*;

 

In my next blog article I’ll be converting my classic Azure SQL script to use the Azure RM new paradigm.

 

PowerShell connecting to SQL Server without SMO

Sometimes there will be a need to provide a scripting solution to connect to SQL Server to execute either a TSQL query or Stored-Procedure without the need of installing a SQL Server bits.  Here I’m providing two code snippets that gets the job done without the use of SMO (SQL Server Management Object) class.

Executing a T-SQL Query

Use the System.Data.SqlClient namespace from the .NET Framework Data Provider for SQL Server in order to build functions to execute T-SQL statement(s) and/or SQL Stored-Procedure with PowerShell.

Here’s an example in how to execute a T-SQL statement querying a table in its basic form:

## - Set PowerShell variables:
$ConnectionString = 'server=YourMachineName\MSSQL2K14;database=Master;Integrated

Security=false;User ID=sa;Password=$myPwd!';
$TSQLQuery = "Select * from AdventureWorks2014.dbo.AWBuildVersion;";

## - Connect and Execute Stored-Procedure:
$sda = New-Object System.Data.SqlClient.SqlDataAdapter ($TSQLQuery, $ConnectionString);
$sdt = New-Object System.Data.DataTable;
$sda.fill($sdt) | Out-Null;
$sdt.Rows;

 

nonSMO_01_10-16-2015

Executing a T-SQL Stored-Procedure

Now the code for executing SQL Stored-Procedure will be differect as we are going to use the ‘.sqlCommand‘ class to process the T-SQL Statement to run a custom table update procedure in its basic form:

## - Set PowerShell variables:
$ConnectionString = 'server=YourMachineName\MSSQL2K14;database=Master;Integrated

Security=false;User ID=sa;Password=$myPwd!';
$TSQLQuery = "Exec [AdventureWorks2014].[dbo].[usp_UpdAWBuildVersion];";

## - Connect and Execute Stored-Procedure:
$sqlCon = New-Object Data.SqlClient.SqlConnection;
$sqlCon.ConnectionString = $ConnectionString;
$sqlCon.open()
$sqlCmd = New-Object Data.SqlClient.SqlCommand
$sqlCmd.Connection = $sqlCon
$sqlCmd.CommandText = $TSQLQuery;
$sqlCmd.ExecuteNonQuery();
$sqlCon.close();

I use dbForge for SQL Server to create new Stored-Procedure to dynamically increase the version number.

nonSMO_dbForge_01_10162015

After executing the non-SMO code then the record did change:

nonSMO_01a_10-16-2015

nonSMO_dbForge_02_10162015

Most important, when using the Data.SqlClient.SqlConnection class, the connection need be ‘.Close()‘ after executing the T-SQL command.

Error Handling

As we are connecting to the SQL Server to execute T-SQL Commands, its important to add some error handling routine to trap errors during the connectivity and/or T-SQL Statement(s) processing.  And, we do this by evolving the basic PowerShell code into a function.

Lets create two functions that will accept two parameters: a connection string, and the T-SQL Query.

* Get-TSQLQuery function

function Get-TSQLQuery
{
Param (
[string]$ConnectionString,
[string]$TSQLQuery
)
Try
{
## - Non_SMO Get SQL query:
$sda = New-Object System.Data.SqlClient.SqlDataAdapter ($TSQLQuery,

$ConnectionString);
$sdt = New-Object System.Data.DataTable;
$sda.fill($sdt) | Out-Null;
$sdt.Rows;
}
Catch
{
Write-Verbose "Error executing T-SQL Query: `r`n[$($error[0])]" -Verbose;
};
};

To test this function copy/paste the code into your PowerShell console, and the execute the following commands:

## - Set PowerShell variables:
$conn = 'server=MTRINIDADLT2\MSSQL2K14;database=Master;Integrated Security=false;User

ID=sa;Password=$Adm1n!';
$tsql = "Select * from AdventureWorks2014.dbo.AWBuildVersion";

## - Execute the function with its parameters:
(Get-TSQLQuery -ConnectionString $conn -TSQLQuery $tsql) `
| Select-Object `
SystemInformationID, 'Database Version', VersionDate, ModifiedDate `
| Format-Table -AutoSize;

nonSMO_02_10-16-2015

* Execute-TSQLStoredProc function

function Execute-TSQLStoredProc
{
Param (
[string]$ConnectionString,
[string]$TSQLQuery
)

Try
{
## - NON-SMO executing TSQL Stored-Procedure:
$sqlCon = New-Object Data.SqlClient.SqlConnection;
$sqlCon.ConnectionString = $ConnectionString;
$sqlCon.open();
$sqlCmd = New-Object Data.SqlClient.SqlCommand;
$sqlCmd.Connection = $sqlCon;
$sqlCmd.CommandText = $TSQLQuery;
$sqlCmd.ExecuteNonQuery();
}
Catch
{
Write-Verbose "Error executing T-SQL Stored-Procedure: `r`n[$($error[0])]"

-Verbose;
}; $sqlCon.close();

};

## - Set PowerShell variables:
$Conn = 'server=MTRINIDADLT2\MSSQL2K14;database=Master;Integrated Security=false;User

ID=sa;Password=$Adm1n!';
$tsql = "Exec x[AdventureWorks2014].[dbo].[usp_UpdAWBuildVersion]";

## - Execute the function with its parameters:
Execute-TSQLStoredProc -ConnectionString $conn -TSQLQuery $tsql;

nonSMO_03_10-16-2015

Adding the Try/Catch error handling block helps is trapping and displaying the errors.

This method serves as another alternative to connect to a SQL Server without the need to install an instance on a system.

 

 

PowerShell Deep Dive session at Work – a Success!

At TBC Corp. (Tire Kingdom) I scheduled the second PowerShell meeting for September 28th close to noon.  A give a 2hr PowerShell Deep Dive where everyone brought their laptops so they could follow along the session.  It was a total success!  I had 15 people signed up and 30 showed up for this session.

TBCPowerShell

This was a diversified group of people which included: System Administrators(Windows, Linus, iSeries, SAP), Data Center Operators, Business Intelligence Developers, SQL Server Administrator and even some Business Analyst.  The general overview went well. The whole group was very interested in learning about PowerShell.

GettingStartedPowerShell_01_9-28-2015 jpg

GettingStartedPowerShell_02_9-28-2015 jpg

It all happened thanks for the support of all the technologies managers which realized this technology need to be adopted and embraced in their daily responsibilities.  This is opening to new opportunities to improve productivity.

I’m honored to be part of TBC Corp organization to allow me to be an “influencer” and provide guidance to this amazing technology.  I thanks Microsoft MVP program for helping me in accomplishing my goals and keeping up-to-date with technology.

I’m planning to do more TBC PowerShell Monthly meetings so they can easily adopt PowerShell and its amazing new features such as Desired State Configuration.

WP_20150928_020

WP_20150928_019

WP_20150928_017

WP_20150928_018

I’m so excited!!

PowerShell Studio working with Datagrid component

I love working with PowerShell. Yes! I admitted. And, I love using SAPIEN Technology “PowerShell Studio” product and specially when I can develop a productive windows application for our Data Center team to use. This make my and their job easy to handle.

SAPIEN_9-4-2015 10-36-39 AM

I just develope a Windows application to handle our company tables updates which monitor failures and recovery via PowerShell. The SAP 3rd party vendor application our team are using is old and doesn’t give any productive way to handle failures and recovery for these nightly tasks. And, here’s where PowerShell comes to the rescue.

So, one on the main components in building this Windows application is the use of the Datagrid. As PowerShell has a very useful Out-Gridview cmdlet but SAPIEN product gives you the .NET Visual Studio look-a-like feel for developing Windows Application.

The recent enhancements to the Out-GridView cmdlet has made it powerful and very useful command:

1. The use of filtering the data.
2. The use of the ‘-passthru” parameter so you select one or multiple items.
3. The use of the “-title” parameter.

SAPIEN5_9-4-2015 10-36-39 AM

SAPIEN6_9-4-2015 10-36-39 AM

Now, getting back to using a Datagrid in a SAPIEN PowerShell Windows Application. PowerShell Studio give us the ability to build Windows application with PowerShell code. For a person that have never use Visual Studio, the learning curve is short thanks to all the Wizards this product have included to get you started.

SAPIEN2_9-4-2015 10-36-39 AM

SAPIEN3_9-4-2015 10-36-39 AM

Now, sometime ago I posted a blog about creating a Windows application with a datagrid. Here’s the link:
1. http://www.maxtblog.com/2015/04/playing-with-powershell-studio-2015-windows-form-12/
2. http://www.maxtblog.com/2015/04/playing-with-powershell-studio-2015-windows-form-22/

After I posted the above blog articles,my MVP friend June Blender, remind me that SAPIEN had a snippet “ConvertTo-DataTable” which can be use to convert the PowerShell object to be loaded to the Datagrid. Here’s the blog link:
http://www.maxtblog.com/2015/05/using-powershell-studio-2015-snippet-sample/

SAPIEN4_9-4-2015 10-36-39 AM

But just recently, while build more applications with Datagrid, I discover that the DateTime value returned in thedatagrid is incomplete and only shows the date.

ConvertTo-DataTable_9-4-2015 8-07-31 AM

So, I went back to my own version that build the object for the datagrid to verify that the datetime values are retained.
Then, I decided to create a function “ConvertTo-DataSetObject” which is a smaller version and seem to work with ‘datetime‘ values loaded to a Datagrid.

ConvertTo-DataSetObject_9-4-2015 8-07-31 AM

Then, I added the function to my User snippet section. Here’s the function “ConvertTo-DataSetObject” code snippet:

function ConvertTo-DataSetObject
{
<# .SYNOPSIS Convert an object to a dataset object for a datagrid. .DESCRIPTION Convert an object to a dataset object for a datagrid by create a global variable "$global:dsObj". .PARAMETER InputObject This parameter will accept any PowerShell variable. .EXAMPLE PS C:\> ConvertTo-DataSetObject -InputObject $psObject

.NOTES
This function is useful when creating object for a datagrid component.
#>
Param (
[object]$InputObject
)

#Create DataSet Object
$global:dsObj = New-Object System.Data.DataSet;

#Create DataTable
$global:dtObj = New-Object System.Data.DataTable("PSObjTable");
$dtCols = $global:dtObj.Columns; $dtRows = $global:dtObj.Rows;

## - Populate Columns
foreach ($c in ($InputObject | gm -MemberType '*Property').Name)
{
$x = 1;
($global:dtObj.Columns.Add().ColumnName = $c);
};

## - Populate Rows:
foreach ($c in $InputObject)
{
## Initialize row:
$nwRow = $global:dtObj.NewRow();

## Data
foreach ($c2 in ($InputObject | gm -MemberType '*Property').name)
{
$nwRow[$c2] = ($c).$c2;
}
## Add row to object:
$global:dtObj.Rows.Add($nwRow);
};

$global:dsObj.Tables.Add($global:dtObj);

};

Here some additional tips when working with datagrid component using the following:

In the Datagrid properties:
1. Add a descriptive text under Captiontext.
2. Set the ReadOnly to True.

Using code to resize all column before display the datagrid:


$datagrid1.PreferredColumnWidth = '120';
:
ConvertTo-DataSetObject -InputObject $d;
$datagrid1.SetDataBinding($dsObj, "PSObjTable");