Welcome PowerShell Core 6.0.0 GA

Yes! Today the Microsoft PowerShell Team with the help of the community has made PowerShell CoreGenerally Available” and “Supported“. Feel free to read their blog post at:
https://blogs.msdn.microsoft.com/powershell/2018/01/10/powershell-core-6-0-generally-available-ga-and-supported/

Get It Now

Of course, there are little housekeeping to do, such as download links still pointing to the older version. But, while they fix the links, you go straight to the “Release” page to individually download the file: https://github.com/PowerShell/PowerShell/releases

Also, on the Linux distribution side, I found out that the auto upgrade stop working. So the following steps will help you install PowerShell Core 6.0.0 in Linux Ubuntu found in the Github “How To Install” link.

Ubuntu Power

Windows 10 WSL

If you have Windows 10 WSL (Ubuntu) install use the same instruction for Ubuntu 16.04:

[sourcecode language=”bash”]
# Import the public repository GPG keys
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add –

# Register the Microsoft Ubuntu repository
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list

# Update the list of products
sudo apt-get update

# Install PowerShell
sudo apt-get install -y powershell

# Start PowerShell
pwsh

[/sourcecode]

So, in either Windows or Linux, must important is to remove/uninstall the previous version. Then, install PowerShell Core 6.0.0.

Remember

Please file any PowerShell Core issues (not Windows PowerShell) in Github at: https://github.com/PowerShell/PowerShell/issues

So, in order to properly address any Windows PowerShell issues, has to be reported on UserVoice at: https://windowsserver.uservoice.com/forums/301869-powershell

As stated in the landing page under “Windows PowerShell vs PowerShell Core” section.

Follow PowerShell Core in Tweeter using #PSCore6 tag.

Simple way to get AzureRM VM Status

This is one of the beauty of PowerShell as you can always find the way simplify your code. In the case of getting the AzureRM virtual machine status using the Get-AzureRMVM cmdlet, everyone has been a little misleaded. It seems at that this command won’t give you the VM status unless you use the ‘-Status‘ parameter.

So, if you don’t use this parameter it won’t display the “PowerState” property, which in fact is the “Status” we all are looking for.

Simplicity

In order to properly display the status of any VM in Azure using AzureRM Get-AzureRMVM cmdlet, then use the following one-liner to do it:

[sourcecode language=”powershell”]
## – Display Status of existing VM’s:
get-AzureRmVM -ResourceGroupName azResourceEast01 -Status `
| Select-Object Name, PowerState;

## – Or, change the Property Label from “PowerState” to “Status”:
get-AzureRmVM -ResourceGroupName azResourceEast01 -status `
| Select-Object Name, @{ label = “Status”; Expression = { $_.PowerState } };

[/sourcecode]

Of course, this will also work in PowerShell Core. (The sample posted is showing Windows 10 Ubuntu)

Additional Information

The following AzureRM versions can be installed from the PowerShell Gallery:

1. For Windows PowerShell: AzureRM Version 5.1.1
2. For PowerShell Core (Windows, Linux,…): AzureRM.Netcore Version 0.9.1

Keep in mind, when installing PowerShell Modules from PowerShell Gallery in Linux need administrator permissions. Open PowerShell using “sudo pwsh“, then proceed to execute “Install-Module AzureRM.Netcore” one-liner.

Then, connect to Azure and execute the command. (Previously shown)

 

PowerShell Core–Updated setup OpenSSH in Windows and Linux

It’s been over a year since my last post on “PowerShell Open Source – Windows PSRemoting to Linux with OpenSSH”. A lot has change, so here’s the updated version.

Linux OpenSSH installation

In Linux (Ubuntu), open a terminal (Bash) session.

Install the following *packages:

sudo apt install openssh-server
sudo apt install openssh-client

*Note: The system will let you know if they already exist.

Need to configure the OpenSSH config file:

sudo gedit /etc/ssh/sshd_config

The, add following line in the “subsystem” area:

Subsystem powershell pwsh.exe -sshs -NoLogo -NoProfile

Proceed to save the file.

Now, execute the following lines:

sudo ssh-keygen –A

Restart the ‘ssh’ service by executing the following command:

sudo service ssh restart

Windows OpenSSH installation

In *Windows Client or Server, open Services to ‘Stop‘/’Disable‘ both SSH Broker and SSH Proxy.

*Note: Latest Windows Insider Builds having the following services previously installed: SSH Broker and SSH Proxy

Open PowerShell Core Console (Run as Administrator):

[sourcecode language=”powershell”]
pwsh

[/sourcecode]

First thing, make sure Chocolatey is installed in PowerShell Core: https://chocolatey.org/install

[sourcecode language=”powershell”]
iex ((New-Object System.Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1’)

[/sourcecode]

*note: Chocolatey Install instructions will run ‘Set-ExecutionPolity Bypass’. The problem is, it won’t change it back to the previous setting.
Make sure to run “Get-ExecutionPolicy” to verify current settings.

Installing OpenSSH package from Chocolatey:

[sourcecode language=”powershell”]
choco install openssh

[/sourcecode]

Close/Reopen PowerShell Core (Run as Administrator), and execute the following command:

[sourcecode language=”powershell”]
refreshenv

[/sourcecode]

Change Directory to the OpenSSH folder:

[sourcecode language=”powershell”]
cd ‘C:\Program Files\OpenSSH-Win64\’

[/sourcecode]

Now, we need to make changes to the sshd_config file with Notepad:

[sourcecode language=”powershell”]
Notepad sshd_config

[/sourcecode]

Need to enabled the following commented out lines:

[sourcecode language=”text”]
Port 22
PasswordAuthentication yes
PubkeyAuthentication yes

[/sourcecode]

Finally, add the subsystem line to include PowerShell Core path:

[sourcecode language=”text”]
Subsystem     powershell    C:/Program Files/PowerShell/6.0.0-rc.2/pwsh.exe -sshs -NoLogo –NoProfile

[/sourcecode]

Save the file and we are ready to configure the firewall rule for port 22.

Windows Firewall Port 22 Setup

Next, confirm that there are no other TCP ports using port 22:

[sourcecode language=”powershell”]
netstat -anop TCP

[/sourcecode]

Now, add the SSH firewall rule for using port 22:

[sourcecode language=”powershell”]
netsh advfirewall firewall add rule name=SSHPort22 dir=in action=allow protocol=TCP localport=22

[/sourcecode]

Open Firewall app and verify it’s added.

Completing Windows OpenSSH Installation

The following steps are essential for the sshd service to start without any issues. Make sure to be at the OpenSSH folder:

[sourcecode language=”powershell”]
## – Generate SSH keys:
ssh-keygen -A

## – Execute both fix permissions scripts:
.\FixHostFilePermissions.ps1 -confirm:$false
.\FixUserFilePermissions.ps1

## – Install both ssh services: sshd and ssh-agent:
.\install-sshd.ps1

[/sourcecode]

Then, set both sshd and ssh-agent services set to start automatically.

[sourcecode language=”powershell”]
Set-Service sshd -StartupType Automatic
Set-Service ssh-agent -StartupType Automatic

[/sourcecode]

At this point, only start service sshd which will turned on the ssh-agent service.

[sourcecode language=”powershell”]
Start-Service sshd
#Start-Service ssh-agent (optional)

[/sourcecode]

Must important, open the *Services MMC console and verify that all running.

*Note: On the server will be needed to set the credential as Local System (see below).

Now, proceed to test connectivity between two system using PowerShell Core.  To test connectivity could use the following command:

Enter-PSSession -hostname systemname -username UsenameHere

Additional Note:

I found an issue when been a member of a domain but the Domain is Off. Trying to restart ssh service, I get the following error:

[sourcecode language=”powershell”]
PS C:\Program Files\OpenSSH-Win64> Start-Service sshd
Start-Service : Failed to start service ‘sshd (sshd)’.
At line:1 char:1
+ Start-Service sshd
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
+ FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand

[/sourcecode]

Or trying to manually start the “sshd” service using the Services MMC:

This error was due to missing a step in the installation:

Resolution: Thanks to Github Win32-OpenSSH @bagajjal provided the following steps:

[sourcecode language=”powershell”]
## – Fixing sshd service not starting with the NET Service credentials:
.\FixHostFilePermissions.ps1 -Confirm:$false
.\uninstall-sshd.ps1
.\install-sshd.ps1
[/sourcecode]

This resolved the sshd start failure. (see below)

Awareness on Installing PowerShell Modules

As you are all aware of the upcoming PowerShell Core, and the impact it will bring in our cross-platform infrastructure. For now, both Windows Powershell and Powershell Core will co-exist side by side. Also, our Powershell skill sets will still be on a high degree of demand in the workplace. This is not going to slow down.

So, let’s create some awareness when installing Powershell modules. Now, we’ve seen a raise of *core modules which are targeted to be use with PowerShell Core for the purpose of installing them in either Windows and/or non-Windows environments. But at the same time, and I have experience, installing different versions of the same module in Windows PowerShell.

Let’s take for example AzureRM modules.

Cloud Module Balance

Let me say you will possibly experience this in the following situation:

1. If you’re install Visual Studio with the Azure SDK
2. If you’re a Developer which are trying to keep up with the latest module but forget to remove the old ones.
3. Also, installing modules from different sources.

Which sources are currently available for installing Azure modules?
(Just to name a few)

1. PowerShell Gallery
2. Azure Download
3. Azure SDK’s (VS Studio installation or standalone)

So, having multiple versions of the same modules may lead to issues such as: deprecated commands, invalid parameters/paramterset, and all leading to broken automation scripts.

It’s been suggested to use the PowerShell Gallery to get the Azure PowerShell Modules. But, always to the proper search for the latest version.

Using Powershell Gallery as the main repository for grabbing PowerShell modules, you can query for the modules before installing them:

1. Set the main repository to be “PowerShell Gallery”:

[sourcecode=”powershell”]
## – Set PowerShell Gallery Repo:
Set-PSRepository `
-Name “PSGallery” `
-InstallationPolicy Trusted;

[/sourcecode]

2. Find the modules you want to install: (In this case, “AzureRM”)
[sourcecode=”powershell”]
## – Find Module(s) in PowerShell Gallery for Windows PowerShell:
Find-Module -Name AzureRM

## – Find Module(s) in PowerShell Gallery for PowerShell Core:
Find-Module -Name AzureRM.Netcore

[/sourcecode]

Now, you can proceed to install the module:

1. Proceed to get the module from PowerShell *Gallery:
[sourcecode=”powershell”]
## – Get/install Module(s) from PowerShell Gallery:
Install-Module -Name AzureRM `
-Repository “PSGallery”;

[/sourcecode]

*Note: Installing AzureRM.Netcore in Linux, you need to use ‘sudo pwsh’.

2. List the installed module(s):(Windows and Linux)
[sourcecode=”powershell”]
## – List of installed AzureRM modules:
Get-Module -ListAvailable AzureRM* `
| Select name, version, path;

[/sourcecode]

At this point, you can start building scripts.

Working with PowerShell Gallery

The following series of commands will get you started working with PowerShell Modules.

1. List all installed modules in system and can help to spot duplicates:
[sourcecode=”powershell”]
## – List of installed all PowerShell modules:
Get-Module -ListAvailable `
| Select Name, Version, Path `
| Sort-Object Name, Version;

[/sourcecode]

2. List installed modules locations in the PSModulePath variable:
[sourcecode=”powershell”]
## – List installed modules locations
$env:PSModulePath.split(‘;’);

[/sourcecode]

These two commands will give you the necessary information to identify and locate all *”installed” modules in yours system.

*Note: This will not include manually custom modules as the are not install thru PowerShell Gallery, or outside of the standard PowerShell Module folders.

Managing your Modules

In order to prevent cluttering your system with modules you may not use, then its time to do some module updates and/or cleanup.

From Github post “…Moving forward, we recommend using the PowerShell Gallery to get the Azure PowerShell modules. We are looking to push out updates to AzureRM more often since we no longer need to update every module we ship in AzureRM, which will speed up the install/update. …

Taking advantage of PowerShell Gallery commands, we can update our installed modules:

[sourcecode=”powershell”]
# Updating the modules in AzureRM
Update-Module -Name AzureRM

[/sourcecode]

This step should prevent us installing multiple versions of the same module. (Update) – But, I discovered that this will cause a duplicate module (different versions) after the Update-Module is completed.

What about module(s) cleanup? The following one-liner can be use to cleanup/remove module(s) that install from the PowerShell Gallery. In the case of cleaning up all AzureRM modules, the following command should remove all *modules:

[sourcecode=”powershell”]
## – This will remove all AzureRM submodules “AzureRM.*:
Get-Module -ListAvailable `
| where-Object {$_.Name -like “AzureRM*”} `
| Uninstall-Module;

## – This will remove the AzureRM main module:
Get-Module -ListAvailable `
| where-Object {$_.Name -like “AzureRM”} `
| Uninstall-Module;

[/sourcecode]

*Note: This command will work as long as you have use the Install-Module to grab the modules from PowerShell Gallery. And, it will take some time to complete.

This way you can start clean and reinstall the modules!

Then, restart your PowerShell session, and use the following command to Get-Module again to list all existing modules.

 

Side-By-Side PowerShell Modules

As, the PowerShell Gallery has become the main repository for PowerShell Module. The Microsoft PowerShell Team has provided a special module to allow Windows Modules to work side-by-side with PowerShell Core:
https://www.powershellgallery.com/packages/windowspsmodulepath/1.0.0

Github post: “… This is currently by-design as we deliberately wanted Windows PowerShell and PSCore6 to work side-by-side with predictability. …

This will assist in identifying what else need to be done PowerShell Core. Just give it a try!

If you find issues with Windows Modules in PowerShell Core, then let the Microsoft PowerShell Team know in Github:
https://github.com/PowerShell/PowerShell

Conclusion

Managing modules when using PowerShell Gallery still is a manual process but easy to use, and even better if you build your own solution. I some instances you may decide to us the old delete or move command to get rid of unwanted modules.

Just take the necessary precautions, and remember, that you could install it back if needed.

Working with Azure Resource Manager Cross-platform with PowerShell Core

This is a brief introduction to connecting to your Azure Cloud subscription using Azure Resource Manager module (AzureRM) in both Windows PowerShell and PowerShell Core. You could install both AzureRM and AzureRM.Netcore modules in the same Windows System. Or, when using Linux, just install the AzureRM.Netcore module.

Azure Resource Manager Installation

In Windows Powershell, use the following command to *install AzureRM (or Azure.Netcore) from the PowerShell Gallery:

[sourcecode language=”powershell”]
## – Install AzureRM from the PowerShell Gallery:
Install-Module -Name AzureRM -Repository PSGallery;

[/sourcecode]

*Note: Keep in mind, the console need to be open with elevated permission or it won’t install the module(s).

In Linux, use “sudo pwsh” to start PowerShell with admin pernmission.

[sourcecode language=”bash”]
$ sudo pwsh

[/sourcecode]

Then, enter the following PowerShell command to install AzureRM.Netcore module:

[sourcecode language=”powershell”]
## – Install AzureRM for PowerShell Core:
Install-Module -Name-AzureRM.Netcore -Repository PSGallery;

[/sourcecode]

To see the list of installed AzureRM in PowerShell, execute the following command:

1. AzureRM Modules. Using the following command will provide the list of modules *loaded:
[sourcecode language=”powershell”]
## – List of installed AzureRM modules:
Get-Module -ListAvailable AzureRM `
| Select name, version, path;

[/sourcecode]

2. In Linux, AzureRM.Netcore Modules. Using the following command will provide the list of modules loaded:

[sourcecode language=”powershell”]
## – List of installed AzureRM.Netcore modules:
Get-Module -ListAvailable AzureRM.Netcore `
| Select name, version, path;

Get-Module -ListAvailable *.Netcore `
| Select name, version, path;

[/sourcecode]


*Note: If you see multiple installation of the same modules, but different versions, you’ll need to pick the right version. Or, this could lead to experiencing having issues when executing azure commands.

You’ll notice that not all Windows PowerShell AzureRM modules has been ported to PowerShell Core yet.

Connecting Linux to Azure Cloud

Here’s where fun begin! We all know in Windows Systems, for automation purpose, we need to create the a certificate key so you can connect to our Azure subscription. But in Linux, is different!

The following steps will connect a Linux System to an Azure subscription:

1. One time only, I use the following command to login to Azure:
[sourcecode language=”powershell”]
## – Login to Azure:
Login-AzureRmAccount;

[/sourcecode]

Executing this command, will have you do a few things:

1. Ask if you want to “enable data collection” (Y/N). (pick one)

2. At this point the command will pause waiting for you to open the browser.

3. Open link provided (copy/paste): https://aka.ms/devicelogin

4. The proceed to enter the code:

5. Enter you Azure email account and password:

6. At the end, you will be asked to close the page and the command will end executiion connecting to Azure.

Try to execute a few AzureRM commands to make sure the connection was successful:

[sourcecode language=”powershell”]
## – Testin Azure connections:
Get-AzureRMSubscription;

Get-AzureRMVM -ResourceGroupName AZRESOURCEEAST01 -Status;

[/sourcecode]

Saving Connection Profile for Automation

After verifying connectivity to Azure, use the following command to save your Azure Subscription Profile in a *Json file. Just give it a location and save the file. This will speed up the *connection step.

[sourcecode language=”powershell”]
## – Save Azure subscription profile: (one time or as needed)
Save-AzureRmContext -Path “/home/username/AzureSubs/lx_ARMprofile.json”;

[/sourcecode]

Next time around connecting to Azure, use the Import command to connect:

[sourcecode language=”powershell”]
Import-AzureRmContext -Path “/home/username/AzureSubs/lx_ARMprofile.json”;

[/sourcecode]

These step works in both Windows PowerShell and PowerShell Core.

Word of Caution

Now, during my venture of moving from Azure Classic modules to Azure Resource Manager (AzureRM) module, I ended hitting the wall. The user experience was rough! It was all due to have duplication modules and different versions, installed in mutliples locations.

There’s a chance that you will encounter the same issues: mostly obsolete/deprecated commands and/or parameters no longer valid. Now, specially if you install Visual Studio, the Azure SDK option might be already an older version.

So, what’s the solution? Definitely, a cleanup is necessary. Then, trust the PowerShell Galery repository to get the latest versions. More in this issue in upcoming post.

For now, don’t stop learning PowerShell!

PowerShell Core 6 Release Candidate is available now

Yes! The Microsoft PowerShell Team has release the PowerShell Core 6 RC to the public this evening 11/17/2017 available for download.  And, now the road to the GA (General Availability) started.

Read all about it on Microsoft PowerShell Team Blog post a the following link: https://blogs.msdn.microsoft.com/powershell/2017/11/17/powershell-core-6-release-candidate/

Notice, when you start PowerShell (pwsh), is giving you a hint to check out PSCpore6-Docs: https://aka.ms/pscore6-docs 

Let’s keep the momentum going!

Streamlining SQL Server Management Objects (SMO) in PowerShell Core

I’ve been recently posting about getting SQL Server Management Objects (SMO) Framework to work in PowerShell Core in both Windows and Linux Systems. So, here’s the revised blog post as the method has kept improving. This way you can start creating some cross-platform SMO PowerShell Core scripts in your environments.

It will works the following way:
1. Windows connecting to Windows SQL Server.
2. Windows connecting to Linux SQL Server.
3. Linux connecting to Linux SQL Server.
4. *Linux connecting to Windows SQL Server.

*Note: Any issues with firewall connecting from Linux to Windows, can be solved by creating the inbound rule for Linux in Windows Firewall.

How to get the SMO for PowerShell Core?

It’s easy! You can get it from NuGet Gallery using PowerShell Core Console. Just make sure you open PowerShell Core as an Administrator to avoid any installation issues.

You could use the following one-liners to find and install the recent SMO package. The following “if-else” code snippet can execute in either Windows or Linux PowerShell Core console.

[sourcecode language=”powershell”]

# Register NuGet package source, if needed
# The package source may not be available on some systems (e.g. Linux)
if (-not (Get-PackageSource | Where-Object{$_.Name -eq ‘Nuget’}))
{
Register-PackageSource -Name Nuget -ProviderName NuGet -Location https://www.nuget.org/api/v2
}else{
Write-Host “NuGet Already Exist! No Need to install.”
}

[/sourcecode]

Installing SMO from NuGet Gallery

After we verified NuGet Package Management is already installed in our system, then we can proceed in Find/Install “SQL Server Management Objects (SMO) Framework“. The current version is “140.17199.0”.

Execute the following one-liner by using the Find-Package to make sure is available. Then, do the install-package command

[sourcecode language=”powershell”]

## – Check that the NuGet feed is available and has the SMO package:
Find-Package -Name Microsoft.SqlServer.SqlManagementObjects

## – Install latest SMO package from NuGet:
Install-Package -Name Microsoft.sqlserver.SqlManagementObjects -Scope CurrentUser

## – Next Line Confirmed Installation:
Get-Package Microsoft.SqlServer.SqlManagementObjects

[/sourcecode]

As of today (November 6th, 2017), the current version of Microsoft.SqlServer.SqlManagementObjects is 140.17199.0. And, it can be installed on either Windows and Linux systems from NuGet.

For more NuGet information about the SMO package, click on the following link: https://www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects

Locating SMO Assemblies and connect to SQL Server

In order to use SMO in PowerShell, we need to know where they are installed. The next one-liner gets the NuGet location to build the path of the SMO installed assemblies.

[sourcecode language=”powershell”]

## – Help find and save the location of the SMO dll’s in a PowerShell variable:
$smopath = Join-Path ((Get-Package Microsoft.SqlServer.SqlManagementObjects).Source `
| Split-Path) (Join-Path lib netcoreapp2.0)

[/sourcecode]

The SMO path is saved. We are ready to load the needed SMO assemblies, to connect and work with SQL Server. The code snippet below will load the SMO assemblies, connect to SQL Server providing necessary credentials:

[sourcecode language=”powershell”]

# 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)

## – Prepare connection and credential strings for SQL Server:
## – (Connection to Linux SQL Server single instance sample)
$SQLServerInstanceName = ‘lxSql00’; $SQLUserName = ‘sa’; $sqlPwd = ‘$Pswrd1!’;

## – (Connection to Windows SQL Server multi-instance sample)
$SQLServerInstanceName = ‘winSql01,1450’; $SQLUserName = ‘sa’; $sqlPwd = ‘$Pswrd1!’;

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

[/sourcecode]

In the previous code sample, I included some variance in providing the SQl Server instance for cross-platform use:
1. In Linux, either using the “SqlServername” or, “IP-Address“.
2. In Windows, either using the “SqlServerName“, or “IP-Address“, or in the case of mutliple instance “SqlServerName,Port“.

Now that the SMO connection to the SQL Server has been established, then we can continue to explore our options using .NET SMO Framework. The Code snippet below shows how to display some of the SQL Server SMO information .NET properties:

[sourcecode language=”powershell”]
## – SMO Get SQL Server Info:

$SQLSrvObj.Information `
| Select-Object parent, platform, product, productlevel, `
OSVersion, Edition, version, HostPlatform, HostDistribution `
| Format-List;

## – End of Code

[/sourcecode]

More SMO Options…

There are additioanl sources providing SMO dll’s:
1.NuGet SMO: https://www.nuget.org/packages/Microsoft.SqlServer.SqlManagementObjects/#
2.GitHub SQLToolService: https://github.com/Microsoft/sqltoolsservice
3.Installing SQL Server mssql-scripter(Python-based): https://github.com/Microsoft/sql-xplat-cli

I’ve been using GitHub “SqlToolsService” for some time now and it works closs-platform. At the same time, I’ve been keeping it up-to-date:
https://github.com/Microsoft/sqltoolsservice/releases

Conclusion

I dare to say! Using .NET SQL Server Management Objects (SMO) Framework, let you be flexible adding control over your scripting. Keep in mind, this is well documented in Microsoft MSDN site: https://docs.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/sql-server-management-objects-smo-programming-guide

My number one choice is to use NuGet Package Management. Although, you can play around with the GitHub SqlToolsService version as it gets frequent updates. The trick in using the GitHub version, is to add the path to where the Dll’s are stored and you’re good to go.

Just Dare to Experiment! Keep learning PowerShell!

Special Thanks to Microsoft: Matteo Taveggia and  David Shiflet for providing me with Nuget PowerShell code piece. I just change it a little!

PowerShell Core – Collecting Information Cross-platform

Now, PowerShell Core has a new look with the new release version Beta.9. At the same time, the executable name has change from “powershell.exe” to “pwsh.exe” (or “pwsh in Linux).

The following example was shown by Microsoft Joey Aiello during the PowerShell Asia Conference in Singapore.  I, kind of, duplicated the steps showing how-to execute one command against two open PowerShell session: one on Linux, and another in Windows.

In my case, I’m on a workgroup environment. So, I have to enable my WinRM and PowerShell Remoting with the following easy steps (just accepting default options):

[sourcecode language=”powershell”]
## – Run quick setup:
winrm quickconfig -force
Enable-PSRemoting -force
.\Install-PowerShellRemoting.ps1

[/sourcecode]

Next, I got to add my trusted hosts in WinRm: adding both IP-Addresses, and system-names. By the way, I didn’t have top manual restart WinRm services.

[sourcecode language=”powershell”]
Set-Item wsman:\localhost\Client\TrustedHosts -Value 10.0.0.19
$curvalue = Get-Item wsman:\localhost\Client\TrustedHosts
Set-Item wsman:\localhost\Client\TrustedHosts -Value “$($curvalue.value), 10.0.0.40”
Get-Item wsman:\localhost\Client\TrustedHosts

Set-Item wsman:\localhost\Client\TrustedHosts -Value “$($curvalue.value), sapien01”
$curvalue = Get-Item wsman:\localhost\Client\TrustedHosts
Set-Item wsman:\localhost\Client\TrustedHosts -Value “$($curvalue.value), earth”
Get-Item wsman:\localhost\Client\TrustedHosts

[/sourcecode]

Next step is to create two open sessions: one on a Linux System and the other to a Windows System. Then verify that both system sessions are opened.

[sourcecode language=”powershell”]
$linuxSession = New-PSSession -HostName venus -UserName maxt
$windowsSession = New-PSSession -ComputerName earth -Credential max_t

Get-PSSession

[/sourcecode]

Please, notice that I’m using the “ssh” protocol to connect to my Linux system, and for Windows I’m using WinRm.

Finally, we can proceed to execute one command against these opened sessions, and see the merged results.

[sourcecode language=”powershell”]
Invoke-Command -Session $linuxSession, $windowsSession -ScriptBlock {Get-Process}

[sourcecode]

Thanks to Joey Aiello for this “Great!” demo showing the possibilities for cross-platform sample in collecting information between different systems.

Go Bold! With PowerShell Core!!

PowerShell Core useful cross-platform variables

In PowerShell Core, there are three useful variable you can use in a cross-platform scripts. Then, the script can have the necessary logic to response based on the environment it is running.

Use the cmdlet Get-Variable to find them, and keep in mind, these variables are not found in Windows PowerShell 5.x.

Get-Variable Is*

Although, the results will display four variable, but let’s pay attention to three of them. Below are the variables with their default values:

IsLinux                            False
IsOSX                              False
IsWindows                    True

These three variables can help in identifying which Operating System the script are been executed.  This way just adding the necessary logic, in order to take the correct action.

For example, you can want to execute a Python code on different systems.

In Windows, if Anaconda (Python 3.6) was installed then Python executable is located at: C:\ProgramData\Anaconda3\python.exe

In Ubuntu Linux, Anaconda (Python 3.6) may be found on user Home folder, then it can be located at:  /home/username/anaconda3/bin/python

Of course, Python location may vary if different versions are installed, and/or installation default location was change.

Sample Cross-platform Code Snippet

Here’s a simple script code logic to accomplished cross-platform behavior.  In my environment the sample code was executes in a Windows system.

[sourcecode language=”powershell”]
if ($IsLinux -eq $true)
{
Write-Host “Executing in Linux – $($psversionTable.platform.ToString())” -ForegroundColor Green;
#Linux Python path:
if ((Test-Path ‘/home/maxt/anaconda3/bin/python’) -eq $true)
{
Write-Host “Linux Python Path Validated” -ForegroundColor Yellow;
}
}
else
{
if ($IsWindows -eq $true)
{
Write-Host “Executing in Windows – $($psversionTable.platform.ToString())” -ForegroundColor Green;
#Windows Python path:
if ((Test-Path ‘C:\ProgramData\Anaconda3\python.exe’) -eq $true)
{
Write-Host “Windows Python Path Validated” -ForegroundColor Yellow;
}
}
else
{
Write-Host “Can’t execute under this OS!”;
};
};

[/sourcecode]

Go ahead and try the same code in Linux PowerShell Core. Of course, this code can be improved, but let’s leave it to your creativity. Start simple and grow!

By the way, did you know you can use SAPIEN Technologies PrimalScript to execute PowerShell Core scripts. Yes! It is possible!

Check the following SAPIEN Blog post about it: https://www.sapien.com/blog/2017/09/15/using-powershell-core-in-primalscript/

SAPIEN PowerShell Tools at Orlando Microsoft Ignite Conference 2017

As I started a new role working for SAPIEN Technologies as their Technology Evangelist in September, I had the opportunity to be working with them a the Microsoft Ignite Conference in Orlando.

Greatly appreciate this opportunity and the chance the meet everyone interested in PowerShell as well as our SAPIEN PowerShell Tools at the event.

Feel free to reach out, keep asking about our product, product services, and must important, give us feedback on how to make it better.

Don’t forget to check out our blog posts, support forums, YouTube videos, and specially the “Information Center” under the following link: https://www.sapien.com/support