Checking for PowerShell Core latest version in non-Windows Systems

I’m not sure who don’t get desperate to get the latest version of PowerShell Core when it becomes available. I do!
Sometimes I’m lucky enough to check Github PowerShell repository to find out it has been recently out.

But, this doesn’t means that is available in any of the other repositories! And, it may take a few more hours after it’s released. So, what would you do?

Repository Availability

Let’s take a look at how to check for PowerShell latest version on different non-Windows Systems.

Ubuntu:
apt-cache policy powershell #-> Or, powershell-preview

CentOS:
yum list powershell #-> Or, powershell-preview

MacOS:
## - Display installed current information.
brew cask info powershell

## - Seems when is current it will not display anything.
brew cask list powershell

## - Intended to show if app is outdated:
brew cask outdated powershell

MacOS Home Brew always takes longer for the new release to be available.

Get It Now!

So, if PowerShell Core isn’t available in the package repository, with a few steps you can download and install PowerShell. But, the first thing I do is to remove it before installing.

Ubuntu

## - When PowerShell Core isn't available in their repository: (download and execute install)
cd Downloads
wget https://github.com/PowerShell/PowerShell/releases/download/v6.1.1/powershell_6.1.1-1.ubuntu.18.04_amd64.deb
sudo dpkg -i powershell_6.1.1-1.ubuntu.18.04_amd64.deb

## - When available in Apt/Apt-Get repository:
sudo apt install -y powershell #-> Or, powershell-preview

CentOS

## - When PowerShell Core isn't available in their repository: (download and execute install)
## - Before removing PowerShell - use Invoke-WebRequest cmdlet.
pwsh
invoke-webrequest https://github.com/PowerShell/PowerShell/releases/download/v6.1.1/powershell-6.1.1-1.rhel.7.x86_64.rpm
sudo yum install powershell-6.1.0-1.rhel.7.x86_64.rpm

## - When available in Yum repository:
sudo yum install powershell #-> or, powershell-preview

MacOS

## - When PowerShell Core isn't available in their repository: (download and execute install)
## - Before removing PowerShell - use Invoke-WebRequest cmdlet.
pwsh
invoke-webrequest https://github.com/PowerShell/PowerShell/releases/download/v6.1.1/powershell-6.1.1-osx-x64.pkg
sudo installer -pkg powershell-6.1.0-osx-x64.pkg -target /

## - When available in Home Brew repository:
brew cask install powershell #-> Or, powershell-preview

Make sure, when in doubt, to check the package management documentation for any of the non-Windows Systems.

Currently Available

As of now, at the time of writing this blog post, the following PowerShell Core versions are available:

  • PowerShell Core (GA) Version 6.1.1 – Release on 11/13/2018
  • PowerShell Core Preview Version 6.2.0-preview.2 – Release on 11/15/2018 (Updated)

More Information

Don’t forget to check the installation instruction for PowerShell Core installation in Github at this link.

Go ahead and give it a try!

Custom PowerShell function to remove Azure Module

As you probably know by now, “Azure RM” modules has been renamed to “Az” Module. Microsoft want you to start using this module moving forward. Currently, this new release is on version 0.5.0, and you’ll need to remove the any previous module(s) installed. Information about Azure PowerShell can be found on the following link.

Now, there’s always been a tedious task when manually removing module dependencies, and there’s no exception with the “Az” module.  So, we can all take advantage to PowerShell and create a script to work around this limitation.

And, below is a few options.

My Custom Function

I have realized that sometimes I got duplicate modules installed with different versions installed, and this can create some confusion. My solution was to create a custom PowerShell function “Remove-AzureModule” to remove all existing Azure modules.

function Remove-AzureModule {
[CmdletBinding(SupportsShouldProcess)]
param ()

$Modules = Get-Module -ListAvailable Az* `
| Select-Object -unique Name, Version;

$cnt = 1;
ForEach ($Module in $Modules)
{
if ($PSCmdlet.ShouldProcess($Module.name, 'Uninstall'))
{
Write-Host "[$cnt] - Removing module: $($Module.Name) - Version: $($Module.Version)." -ForegroundColor Yellow;
Uninstall-Module -Name $Module.Name -AllVersions -Force;
$cnt++;
};
};
};

## - Run using the -What If parameter:
Remove-AzureModule -What If

## - Execute to remove Azure modules:
Remove-AzureModule

The purpose of this function to do a full cleanup removing all installed versions of Azure modules from PowerShell.   This function includes a the “-WhatIf” parameter that can be use to run the function without actually performing the “uninstall” process. And, I added a counter for each module when performing the “uninstall” for each of the dependency module.

Then, you can always use the following “Get-Module” command to verify that all modules has been removed.

Get-Module -Listavailable Az* | Select-Object Name, Version

Azure Docs – Uninstall modules with dependencies

Now, while writing this quick blog post, I found in the Microsoft documentation there’s a “Uninstall the Azure PowerShell Module” section. This article provide the “Uninstall-AllModules” function which is a a generic way to remove any previously installed module with dependencies.

Below, is the modified version of the Microsoft function. I added the code to allow the use of the “-What If” parameter, and to do a count of the modules been removed. I think these are a nice to have changes.

## - Uninstall-AllModules from the Microsoft Docs: https://docs.microsoft.com/en-us/powershell/azure/uninstall-azurerm-ps?view=azurermps-6.12.0#uninstall-from-powershell
## - Modified to include the "-WhatIf" parameter and a module counter.

function Uninstall-AllModules
{
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory = $true)]
[string]
$TargetModule,
[Parameter(Mandatory = $true)]
[string]
$Version,
[switch]
$Force
)

$AllModules = @()

'Creating list of dependencies...'
$target = Find-Module $TargetModule -RequiredVersion $version
$target.Dependencies | ForEach-Object {
$AllModules += New-Object -TypeName psobject -Property @{ name = $_.name; version = $_.minimumVersion }
}
$AllModules += New-Object -TypeName psobject -Property @{ name = $TargetModule; version = $Version }

$cnt = 1;
foreach ($module in $AllModules)
{
Write-Host ("[$cnt] - " + 'Uninstalling {0} version {1}' -f $module.name, $module.version);
$cnt++;
try
{
if ($PSCmdlet.ShouldProcess($module.name, 'Uninstall'))
{
Uninstall-Module -Name $module.name -RequiredVersion $module.version -Force:$Force -ErrorAction Stop;
};
}
catch
{
Write-Host ("`t" + $_.Exception.Message)
}
}
};

## - Example using -WhatIf parameter:
Uninstall-AllModules -TargetModule Az -Version 0.3.0 -Force -WhatIf

## - Example to remove module with dependencies:
Uninstall-AllModules -TargetModule Az -Version 0.3.0 -Force

Unfortunately, this solution will work as long as all dependencies modules has the same version.  So, a little work still need to be done!

Feel free to test the code in both Windows PowerShell and PowerShell Core.

Another way to Manage PowerShell Modules

Take a look at SAPIEN Technologies new product “Module Manager“. You’ll be surprise what you can find installed in your system. This GUI application let you manage modules installed in your system making it easy to update, disable/enable, and install/uninstall modules.

For more Module Manager Preview information check on the following SAPIEN Technologies link.

Recap

As you can see, PowerShell can provide the means to workaround issues you’ll experience in a simple way. At the same time there are both community and Microsoft documentation available that will provide assistance.

Finally, check out third-party products, like the ones from SAPIEN Technologies that are available to increase your productivity in many ways. For more information check on the following SAPIEN Technologies products link.

PowerShell Core 6.1.0 GA (Generally Available) for Anything Anywhere

Any System, Anywhere

Finally the next PowerShell Core GA (Generally Available) at: PowerShell Core 6.1.0. Thanks to the strong effort of both the Microsoft Team and the PowerShell Community has help reach this milestone achievement with the next generation of PowerShell.

 

Announcing PowerShell Core 6.1

Check Jeffrey Snover (Inventor of PowerShell) at MS Ignite 2018 comments about PowerShell (theCube-video)

PowerShell Core will continue to grow providing new features and performance improvements. This version is fully supported.

Anyone can join and contribute at the Microsoft PowerShell Team – Monthly PowerShell Community Call every third Thursday of the month.

To download and install PowerShell Core, go to their Github Repository.

Install Anywhere

Instructions on how to installed it are also available under Microsoft Documentation for both Windows and non-Window systems: MacOS, Ubuntu, Red Hat, CentOS, Fedora, and others Linux distributions.

For more information about installing PowerShell Core, check it out on Microsoft Doc site

For now, this next generation of PowerShell, Windows PowerShell Snap-ins are no longer supported, and the Out-Gridview cmdlet won’t work.

Reporting Issues

Any PowerShell Core feedback should be submitted to its Github repository. And, any Windows PowerShell issues need to be submitted to the UserVoice forum.

Check the Github PowerShell Core landing page, under the “Windows PowerShell vs PowerShell Core” section.

Modules Availability

Only in Windows Systems, Windows PowerShell modules are also available for PowerShell Core. This means that you can open PowerShell Core console and use the existing Microsoft Windows PowerShell modules.

Now, there’s no excuses for not to try using PowerShell Core in Windows Systems.

In the PowerShell Core console, just execute the following command line to list all modules listed in Windows:

Get-Module -ListAvailable

You’ll notice there’s a new column “PSEdition”, which identifies for which version of PowerShell the module will work:
1. Core – for PowerShell Core any system, any where.
2. Desk – for Windows PowerShell.
3. Core\Desk – for PowerShell Core and Windows.

PowerShell Modules location are listed:

1. Users Modules: C:\Users\max_t\Documents\PowerShell\Modules or C:\Users\max_t\Documents\WindowsPowerShell\Modules
2. General Modules for PowerShell Core: C:\Program Files\PowerShell\Modules or C:\program files\powershell\6\Modules
3. General use Modules for Windows PowerShell: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules

Things are changing quickly in the PowerShell Gallery, which was recently update. Any PowerShell Module author has the responsibility to make the necessary update to their modules. Notice that some PowerShell Core modules are still labeled “Desk” when in fact should be both “Core\Desk”, like the “SQLServer” module.

Just make sure to check the module information for which version of PowerShell the module was created for.

Azure Cloud Shell GA (Generally Available)

Yes! Microsoft Cloud Shell has been updated to have PowerShell Core 6.1.0 GA, and is on Linux.

  

This shows the commitment of having cloud reliable solutions running anywhere on any systems.

  • User either Bash or PowerShell in Linux
  • Drag/Drop files into the Browser session
  • AzureRM Module already installed and updated to latest version
  • AzureRM Modules build on .Net Core

In summary

  • PowerShell Core is the next iteration of PowerShell built using .NET Core
  • Run self-contained, side-by-side in Windows systems with Windows PowerShell
  • Cross-platform availability for managing Anything, Anywhere.
  • Microsoft Open Source and Community-support
  • Azure Cloud support

MS Ignite 2018 – PowerShell Videos

Here’s just a couple of interesting videos from the Microsoft Ignite 2018 event in Orlando about PowerShell Core:

Go ahead and try PowerShell Core 6.1 GA! Embrace the change!

Installing MS SQL Server in Ubuntu 18.04

This has been an issue for sometime until now. I found the following link that help me install SQL Server on the latest Ubuntu 18.04:

https://askubuntu.com/questions/1032532/how-do-i-install-ms-sql-for-ubuntu-18-04-lts

But, there are few missing steps which can help ease the burden of errors. At the same time, the information is a little out-dated.

But, it works with the following adjustments.

Please Understand!!  This is NOT approved by Microsoft.  Use this method for Test Only!!

Create Your Installation

The following instructions help you download and get the dpkg package ready for you Ubuntu 18.04 SQL Server installation:

  • Create the folders to extract, and make changes to repackage the dpkg SQL Server installation:
cd ${HOME} && mkdir -p tmp/mssql/newpkg/DEBIAN/ && cd tmp/mssql
  • Download the latest version of SQL Server dpkg to the current folder location: (dpkg SQLServer date: 20-Jun-2018 18:03)
wget https://packages.microsoft.com/ubuntu/16.04/mssql-server-2017/pool/main/m/mssql-server/mssql-server_14.0.3029.16-1_amd64.deb
  • Extract the dpkg package:
dpkg-deb -x mssql-server_14.0.3029.16-1_amd64.deb newpkg/
dpkg-deb -e mssql-server_14.0.3029.16-1_amd64.deb newpkg/DEBIAN/
  • Next step will change the OpenSSL version to avoid failure during SQL Server installation:
sed -i -e 's#openssl (<= 1.1.0)#openssl (<= 1.1.0g-2ubuntu4.1)#g' newpkg/DEBIAN/control
cat newpkg/DEBIAN/control | grep openssl
  • Next step it to Repackage the SQL Server installation:
sudo dpkg-deb -b newpkg/ 18.04-mssql-server_14.0.3029.16-1_amd64.deb

At this stage you could try to install SQL Server, but it might failed.  This is needed in order to check what dependencies are missing. Then, make the necessary dependencies installation.

Additional Steps

As of today, July 5th, I went thru a series of trial-and-error to get my SQL Server running on my Ubuntu 18.04.

After executing the following command:

sudo dpkg -i 18.04-mssql-server_14.0.3029.16-1_amd64.deb

But, I got errors:

The following is the list of all my missing dependencies on Ubuntu 18.04 for the SQL Server installation:

dpkg: dependency problems prevent configuration of mssql-server:
mssql-server depends on libjemalloc1; however:
Package libjemalloc1 is not installed.
mssql-server depends on libc++1; however:
Package libc++1 is not installed.
mssql-server depends on libcurl3; however:
Package libcurl3 is not installed.
mssql-server depends on openssl (<= 1.1.0); however: Version of openssl on system is 1.1.0g-2ubuntu4.1. mssql-server depends on python (>= 2.7.0); however:
Package python is not installed.
mssql-server depends on libsss-nss-idmap0; however:
Package libsss-nss-idmap0 is not installed.
mssql-server depends on gawk; however:
Package gawk is not installed.

Now, one thing to understand, if you execute the following command:

sudo apt install -f

It will clear/remove SQL Server installation components, but it also try to install some, but not all of the dependencies.

As is shown in the image, only two of the listed dependencies were installed: “gawk“, and “libsigsegv2” (this one might be from another package not for SQLServer).

So, identifying the missing dependencies can alleviate the burden of more fail attempts to install SQLServer.

The following command will install all on the listed failed dependencies, excluding OpenSSL because another version is already installed.

## - Adding the missing dependencies:
sudo apt install python libjemalloc1 libc++1 libcurl3 libsss-nss-idmap0

After all the missing dependencies are installed than I can proceed to rerun the re-package SQL Server installation for my Ubuntu 18.04. By the way, I already took care of the OpenSSL in the “Create Your Installation” step where I change the version number.

About Python Dependency?

Yes! In Ubuntu 18.04, Python version 3.6.5 is the one installed with the OS. So, Python 2.7 is not installed.

Try running the command: python –version, then python3 –version at the Terminal Console.

In order to install SQL Server in Linux, it need Python 2.7 installed in order for the installation to work. This is why I included Python in the “sudo apt install …” command to be installed with the other missing dependencies.

Finally Ready

So, finally all the dependencies have been installed. Now, I can rerun the SQL Server installation:

sudo dpkg -i 18.04-mssql-server_14.0.3029.16-1_amd64.deb

This time the installation completes without any error.

To verify that SQL Server is running, execute to following command:

sudo service mssql-server status

Next, verify from your Windows client and open SQL Server Management Studio to verify that the Ubuntu 18.04 SQL Server is accessible.

What’s Next?

Well, if you got PowerShell Core installed, then get the SQLServer Module and start to play around working with both the available cmdlets and/or start coding SMO (SQL Server Management Object) PowerShell Core scripts.

Be creative!  Check out my previous blog post “PSCore6 – SQLServer Module Expanding The Barrier Cross-Platform” for more information.

In Summary

This is a hacking technique to be able to install SQL Server in Ubuntu 18.04.  This is not supported by Microsoft, but you will be able to make it work. Basically, is a matter of installing all the missing dependencies, and change the package required OpenSSL version number to the one installed in Ubuntu 18.04.  Then, repackaging the SQL Server installation dpkg file will allow the installation to work.

Special Thanks to the contributor in the UbuntuAsk forum, as without it I won’t have figured out, and made it work

 

Windows 10 Insider Build 17704 missing PowerShell PSReadLine Module

There has been some noise around “Whatever happened to PSReadLine on this build?“. Well, its a very vague comment. And, due to I’ve been working more with PowerShell Core then I’m starting to stop paying attention to Windows PowerShell.

What did happened with Build 17704?

OK!! So, Windows PowerShell in Build 17704 is missing the PSReadLine Module. So, the workaround is simple to download it from the PowerShell Gallery.

Except! That you need version 2.0.0 (not 1.2).

Check the link: https://www.powershellgallery.com/packages/PSReadLine/2.0.0-beta2

This is good thing because you can install and uninstall module when version 2.0.0 final release get published.
You don’t want to use version 1.2.

Installing PSReadLine in Windows PowerShell

The following command will install the 2.0.0-beta2:

Install-Module -Name PSReadLine -AllowPrerelease -Repository PSGallery

I’m hoping this will help!

 

There’s no issues with PowerShell Core and PSReadLine Module!

 

Installing PowerShell Core 6-Preview.3 in Ubuntu 18.04 and CentOS 7

As you may notice, only the deb package for PowerShell 6-Preview.3 is available for installation. So, only when it becomes GA (Generally Available), then we’ll see the repository documentation included for Ubuntu 18.04 and CentOS 7 installation.

But, don’t worry! Below are some undocumented steps for installing PowerShell Core Preview.3 release.

Installing PowerShell Core 6-Preview.3

1. Download PowerShell Core dpkg *deb for Linux Ubuntu 18.04 or the *rpm package for CentOS 7 from the Release page, and look:
https://github.com/PowerShell/PowerShell/releases/tag/v6.1.0-preview.3

2. Then, execute the next two lines because the first one will not complete successfully:

-For Ubuntu 18.04 dpkg *deb package-

sudo dpkg -i powershell-preview_6.1.0-preview.3-1.ubuntu.18.04_amd64.deb
sudo apt-get install -f

-For CentOS-

sudo yum install powershell-preview-6.1.0-preview.3-1.rhel.7.x86_64.rpm

In either Ubuntu and CentoOS, the installation will seems that will complete without any failures. But, when typing pwsh will not work.

Use the following workarounds if you feel is convenient to use.  Please skip to the “Things Are Changing!” and check out “Undocumented Tips” section.

Execute PowerShell Core – Workaround #1

Type the full path, and PowerShell Core will start:

/opt/microsoft/powershell/6-preview/pwsh

But, of course we don’t want to do this every time.

Execute PowerShell Core – Workaround #2

So, let Just add the PowerShell Core path to the user ~/.bashrc file, follow with reloading Bashrc:

echo ‘export PATH=”$PATH:/opt/microsoft/powershell/6-preview”‘ >> ~/.bashrc
source ~/.bashrc

After all this done, now we can start PowerShell Core from the Ubuntu 18.04 terminal.

Things Are Changing!  (Added – 06/14/2018)

Please make sure to read the PowerShell Core v6.1.0-preview.3 Release Notes.  It announce changes to the PowerShell Core executable for both Linux Distro and MacOS. So, although the above workaround mention works, you can just open PowerShell Core Console by typing “pwsh-preview”.

Undocumented Tips  (Added 06/16/2018)

Repo installation is available!

Most important to be aware of these few tips. You won’t find PowerShell 6.1.0-Preview.3 in any repository. But, there is a PowerShell-Preview.

Now, uninstalling PowerShell Core if you got the PowerShell 6.1.0-Preview.2 installed, then it need to:

  • Ubuntu

sudo apt remove powershell

  • CentOS 7

sudo yum remove powershell

But, in the case you need to remove or reinstall PowerShell Core Preview.3 in either Ubuntu and CentOS then use:

  • Ubuntu 

sudo apt remove powershell-preview

  • CentOS 7

sudo yum remove powershell-preview

Now, to install PowerShell Core Preview.3, beside been able to use either the dpkg *deb package for Ubuntu or the *rpm package to install it, you can use the following command:

  • Ubuntu

sudo apt install powershell-preview

  • CentOS 7

sudo yum install powershell-preview

It works!

These instruction was not documented at the time of the release of PowerShell Core Preview.3.

Thanks for the PowerShell Core Github Community for all the information available about PowerShell Core installation. I know this documentation will be eventually updated in due time.

 

Be Bold! Learn PowerShell Core!

PSCore6 – Creating a Hybrid Cross-platform SQLServer Script

There’s some discussion around scripting on using Windows PowerShell vs PowerShell Core. So, just pick one? No.
Just think about supporting a cross-platform environment. Use both!

Following my recent post on “PSCore6 – SQLServer Module Expanding The Barrier Cross-Platform“, here’s a sample Hybrid-Script for cross-platform use.

Why not!

We all know the next generation (or evolution) of PowerShell is PowerShell Core. That’s it!
You are still using PowerShell, and Windows PowerShell is not going to be dropped nor removed any time soon.

So, why not start working towards, what I call, “Hybrid-scripting”? Powershell Core provides the necessary elements to help with cross-platform scripting.

In it’s basic code form, could look be something like this:

[sourcecode language=”powershell”]

## – Logic Structure for executing either PowerShell Version:

## – Use Set-StrictMode for debug purpose:
Set-StrictMode -Version 5.1

If ($PSversionTable.PSEdition -eq "Desktop") {
"Windows PowerShell"
}
else {
## – Use Set-StrictMode for debug purpose:
Set-StrictMode -Version 6.1

if ($PSVersionTable.PSEdition -eq "Core") {
If ($IsWindows) {
"WindowsCore"
}
If ($IsLinux) {
"LinuxCore"
}
If ($isMacOS) {
"MacOSCore"
}
}
};

[/sourcecode]

Now, let’s apply this code to a practical sample.

Sample Hybrid-Script

In the following sample script, includes Help information, begin-process-end and with try-catch code structure.
At the same time, the script will output the exception to the screen console with the failed line.

Script function name: Get-DBASQLInformation

[sourcecode language=”powershell”]
Function Get-DBASQLInformation {</pre>
<#
.SYNOPSIS
This is a cross-platform function to Get SQL Server Information.

.DESCRIPTION
This is a cross-platform function to Get SQL Server Information using SQL Authentication.

.PARAMETER UserID
Enter SQL Authentication UserID parameter.

.PARAMETER Password
Enter SQL Authentication Password parameter.

.PARAMETER SQLServerInstance
Enter SQLServerInstance name parameter.

.EXAMPLE
PS> Get-DBASQLInformation -UserID ‘sa’ -Password ‘$SqlPwd01!’ -SQLServerInstance ‘mercury,1433’

.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2018 v5.5.152
Created on: 5/25/2018 8:27 AM
Created by: Maximo Trinidad
Organization: SAPIEN Technologies, Inc.
Filename: Function_Get-DBASQLInformation.ps1
===========================================================================
#>
<pre>[CmdletBinding()]
[OutputType([psobject])]
param
(
[Parameter(Mandatory = $true,
Position = 0)]
[string]
$UserID,
[Parameter(Mandatory = $true,
Position = 1)]
[string]
$Password,
[Parameter(Mandatory = $true,
Position = 2)]
[string]
$SQLServerInstance
)

BEGIN {

## – Internal function:
function GetSqlInfo {
param
(
[parameter(Mandatory = $true, Position = 0)]
[string]
$U,
[parameter(Mandatory = $true, Position = 1)]
[string]
$P,
[parameter(Mandatory = $true, Position = 2)]
[string]
$S
)
Try {
## – Prepare connection passing credentials to SQL Server:
$SQLSrvConn = New-Object Microsoft.SqlServer.Management.Common.SqlConnectionInfo($S, $U, $P);
$SQLSrvObj = new-object Microsoft.SqlServer.Management.Smo.Server($SQLSrvConn);

## – SMO Get SQL Server Info:
$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;

}
catch {
## – Write Exception to Console:
Write-Host `
"Excepion found on line:`r`n$($error[0].InvocationInfo.line)"+ `
"`r`n$($Error[0].Exception)" `
-ForegroundColor Magenta;

}
}

};

PROCESS {

## – Cross-platform logic:
If ($PSversionTable.PSEdition -eq "Desktop") {
Write-Host "Windows PowerShell"
GetSqlInfo -U $UserID -P $Password -S $SQLServerInstance;
}
else {

if ($PSVersionTable.PSEdition -eq "Core") {
If ($IsWindows) {
Write-Host "Windows PScore";
}
If ($IsLinux) {
Write-Host "Linux PSCore";
}
If ($isMacOS) {
Write-Host "MacOS PSCore";
}
## – execute on non-Windows:
GetSqlInfo -U $UserID -P $Password -S $SQLServerInstance;
}
};

};

END {
## – EndBlock (Optional)
};
};

[/sourcecode]

The heart of the code are stored in the “Begin” section as a Internal-Function GetSQLInfo(). The internal-function will be only executed if it the criteria for each of the different platforms. The Try-Catch is just to trap the error if the SMO connection failed, or to indicate the SMO .NET wasn’t loaded.

Go ahead! Create a script file, copy/paste this code, and load this function. Give it a try cross-platforms: Windows, Linux, and MacOS.

Remember, SQLServer module is a replacement for SQLPS module. I won’t recommend having both modules installed unless you use the namespace_module/cmdlet to identify which module is going to execute the cmdlet.

So make sure to always test your scripts.

What’s Next!

This function still need to worked on, but is functional enough to test-drive and see the results. So, it be modified to support Windows Authentication. Once you start scripting and building functions, you won’t stop thinking what else can be added.

Just keep working on it and learning from the PowerShell Community.

Go Bold! Learn PowerShell Core!

PSCore6 – SQLServer Module Expanding The Barrier Cross-Platform

If you haven’t heard yet! The SQLServer Module is available for Windows, Linux, and MacOS. Yes!
And, with it,now you can even expand your scripting using .NET SQL Server Management Objects to manage your SQL Server Engine cross-platform.

How to get it!

It’s available in PowerShell Galley. Just run the following command to install the module in Windows PowerShell and PowerShell Core.
Yes, you read it! Install in PowerShell Core for Windows, Linux, and MacOS.

[sourcecode language=”powershell”]

Install-Module -Name SQLServer -Force -Scope AllUsers

[/sourcecode]

What’s in it?

Contains all of the SQL Server Management Objects .NET assemblies that will work in both Windows and non-Windows Systems. At the same time, it contains a total of 63 commands. This will support all existing SQL Server 2017(and older) on your network. Of course, there will be some limitations because there might be some features lacking in older features. But, for most use it will work.

It also includes the ability to provision the SQLSERVER: drive when you import the module.

[sourcecode language=”powershell”]

Import-Module SQLServer

Get-PSDrive

[/sourcecode]

If you care for what SMO .NET Assemblies are installed, execute the following commands:

[sourcecode language=”powershell”]

## – Get the SQLServer Module path:
(Get-MOdule -ListAvailable SQLServer).path

## – List of all SQLServer and Analysis Services DLL’s:
dir ‘C:\Program Files\PowerShell\Modules\SqlServer\21.0.17262\*.dll’ `
| Where-Object{$_.basename -match ‘SqlServer|Analysis’} `
| Format-Wide;

## Linux CentOS – Total of SQLServer and Analysis Services DLL’s:
(Get-ChildItem ‘/usr/local/share/powershell/Modules/SqlServer/21.0.17262/*.dll’ `
| Where-Object{ $_.basename -match ‘SqlServer|Analysis’ }).count

[/sourcecode]

Using the SQLServer: Drive

Although, I’m not a fan of using SQLServer: drive. This will allow you to navigate thru the SQL Engine like a file system from the console prompt.

In order to use the drive, it need to be recreated with the proper credentials for cross-platform use.
Below steps will create additional SQLServer: drives to another SQLServer on the *network.

[sourcecode language=”powershell”]
###==>For Windows, Linux, MacOS
Import-Module SqlServer

## – New way for Streamlining Get-Credential:
$MyUserName = ‘sa’; $MyPassword = ConvertTo-SecureString ‘$SqlPwd01!’ -asplaintext -force;
$MyCred = [System.Management.Automation.PSCredential]::new($MyUserName, $MyPassword)

## – Creating SQLSERVER: connection to Windows SQLServer:
New-PSDrive -PSProvider sqlserver -root “SQLSERVER:\SQL\sapien01,1451\default” -name MyWindowsSQL -Credential $mycred

## – List all SQLSERVER: Drives:
Get-PSDrive *SQL* | Select-Object Name, Provider, Root;

[/sourcecode]

 

Note: In this example, I’m using SQL Authentication.

Now, I can navigate thru my SQLServer objects like a filesystem.

[sourcecode language=”powershell”]

## – Change directory to SQLSERVER: drive:
cd MyWindowsSQL:/databases/sampledb1/tables
dir

[/sourcecode]

Wait! Did you notice I’ve created a SQLServer Drive in MacOS? This is Awesome!
By the way, there’s no Docker involved in here. The fun doesn’t stop here!

What about using SMO scripting?

If anyone have been following me recently, everytime I’ve created the SMO script, I always have to load the assemblies before I can connect to the SQLServer.

[sourcecode language=”powershell”]

## – When using the ‘Microsoft.SqlServer.SqlManagementObjects’package installed from Nuget
## – Help find and save the location of the SMO dll’s in a PowerShell variable: ver.14.17224
$smopath = Join-Path ((Get-Package Microsoft.SqlServer.SqlManagementObjects).Source `
| Split-Path) (Join-Path lib netstandard2.0);

# Add types to load SMO Assemblies only:
Add-Type -Path (Join-Path $smopath Microsoft.SqlServer.Smo.dll);
Add-Type -Path (Join-Path $smopath Microsoft.SqlServer.ConnectionInfo.dll);

[/sourcecode]

The above code is not needed if the SQLServer module had been previously imported.
This way you will code less.

Here’s a small SMO script example for getting SQLServer information using SQL Authentication:

[sourcecode language=”powershell”]

## SMO with Import-Module SQLServer
Import-Module SQLServer

## – Prepare connection strings and connect to SQL Server
$SQLServerInstanceName = ‘mercury,1433’;
$SQLUserName = ‘sa’; $sqlPwd = ‘$SqlPwd01!’;

## – Prepare connection to SQL Server:
$SQLSrvConn = new-object Microsoft.SqlServer.Management.Common.SqlConnectionInfo($SQLServerInstanceName, $SQLUserName, $SqlPwd);
$SQLSrvObj = new-object Microsoft.SqlServer.Management.Smo.Server($SQLSrvConn);

## – SMO Get SQL Server Info:
$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;

[/sourcecode]

As you can see, there’s no reason why not try and experiment using PowerShell Core with SQL Server.  Next blog post I’ll be creating this script code in the hybrid-script function that can be executed cross-platform. I mean, on any PowerShell version too.

What’s in the future!

Now that PowerShell SQLServer Module is available cross-platform, I will see others Community SQL modules (DBATools, DBAReports) making their way to PowerShell Core. Of course, it will take some before it becomes available!

In the meantime, you can use SMO to build your own PowerShell SQL Scripts. Why not! Go and Expand your horizon!!

Be Bold! Learn PowerShell Core!

PSCore6 – Export-CSV cmdlet difference

Yes! There’s a change, and is a good one. While checking out some recent blog post on Export-Csv command, I took it a little further. And, I ended up finding that the parameters have change in this cmdlet.

Difference

Export-Csv – Windows Powershell parameter names:

[sourcecode language=”powershell”]
((Get-help Export-Csv).Parameters).parameter.name
Append
Confirm
Delimiter
Encoding
Force
InputObject
LiteralPath
NoClobber
NoTypeInformation
Path
UseCulture
WhatIf

[/sourcecode]

Export-Csv – PowerShell Core parameter names:

[sourcecode language=”powershell”]
((Get-help Export-Csv).Parameters).parameter.name
Append
Confirm
Delimiter
Encoding
Force
IncludeTypeInformation
InputObject
LiteralPath
NoClobber
NoTypeInformation
Path
UseCulture
WhatIf

[/sourcecode]

Notice in PowerShell Core, there’s a new parameter: “-IncludeTypeInformation“.

Our prayer answered!

For a long time, in Windows PowerShell, we had to add the parameter “-NoTypeInformation“, so the “#TYPE …” line on the first row of the *CSV would not be included.

So, in Windows PowerShell executing the command without the “-NoTypeInformation” parameter, will produce the following result:

Now, using the same command in PowerShell Core without the “-NoTypeInformation” parameter, will produce a different result:

Moving forward with PowerShell, there’s no need to include the “-NoTypeInformation” parameter. Apparently, seems like the “-NoTypeInformation” parameter is the default when is not use in the cmdlet. So, no changes are needed to any previous developed scripts.

Clean Data

There is one thing we’ve learn thru time, is to always provide clean data. Knowing that a *CSV file is a text data set with columns and rows, always provide the columns name(s). This way the data structure looks nice and well defined.

Here’s just an example of how to manually create a one column list: (PowerShell Core)

[sourcecode language=”powershell”]
## – First add the column name, then add the rows:
‘ServerName’ | Out-File -LiteralPath c:\Temp\MyServerList.csv;
@(‘Server1′,’Server2′,’Server3’) | Out-File -LiteralPath c:\Temp\MyServerList.csv -Append;

## – Display the CSV file on Console:
cat c:\Temp\MyServerList.csv

## – Import the *CSV file into a PSObject:
$csvObj = Import-Csv -LiteralPath c:\Temp\MyServerList.csv;
$csvObj

ServerName
———-
Server1
Server2
Server3
[/sourcecode]

It is better to use the Out-File cmdlet in this scenario. Also, let say you got multiple *CSV file with the same data structure, meaning the same column name(s). To merge into a single object the following one-liner can solve the problem:

[sourcecode language=”powershell”]
## – Display on screen before creating the PSObject:
(Get-ChildItem C:\Temp\MyServer*.csv).FullName | import-csv

## – Build the PSObject:
$csvAllObj = (Get-ChildItem C:\Temp\MyServer*.csv).FullName | import-csv
$csvAllObj
[/sourcecode]

Export PSObject to CSV

Now, the PSObject was created, go back and use the Export-Csv to create the *CSV file.

[sourcecode language=”powershell”]
$csvAllObj | Export-csv -LiteralPath c:\Temp\MyPSObjectServerList.csv

cat c:\Temp\MyPSObjectServerList.csv
"ServerName"
"Server1"
"Server2"
"Server3"
"Server4"
"Server5"
"Server6"
"Server7"
"Server8"
"Server9"
[/sourcecode]

Finally, a *CSV file was properly created!

Bottom line

The Export-Csv is meant to be use with well-structured PSObjects and is not meant to be use from a text file.

Of course, there are many other ways to get things done with PowerShell and that’s the beauty of it.
There’s always a way!

Be Bold!! Learn PowerShell Core!!

Quick blog on – How to recover/rebuild Master Database in Linux?

Back in March 30th, I posted a suggestion on SQL Server forum, about there was no documentation on how to rebuild SQL Server System database(s) in Linux.

https://feedback.azure.com/forums/908035-sql-server/suggestions/33805198-sql-server-2017-on-linux-system-databases-rebuild?tracking_code=befe44dc3ccdd27370ef0f54c9c8c975

The Issue – SQL Server stopped working

For some reason, I finished doing an “sudo apt update” follow by the “sudo apt upgrade“, and after doing some OS updates “my SQL Server stopped working”. The following message was logged in the log event: (see Image)

Command executed, looking at the last log entry:  “sudo cat /var/opt/mssql/log/system_health_0_131668975728890000.xel

I look everywhere for more information but found no blog post or any documentation about it.

To my surprise! I got a quick response which I appreciate very much.

The Answer

Execute the following command in the user context
/opt/mssql/bin/sqlservr –force-setup

And, will be seen this added to the SQL Server 2017 Linux documentation.

Thanks Microsoft!!

Remember

In Ubuntu I use the following command to check the status of my SQL Server instance:

sudo systemctl status mssql-server

Make sure the status is: active: (running)!

So, Backups are important! Even in Linux.  In my case, I’m running demos and love the fact that reinstalling SQL Server only took a few minutes. But, now I know another way to solve this issue!

And, the Mic is Dropped!!