Friday 27 August 2021

Installing PowerShell 7

I installed PowerShell 7 because I wanted to use the Background operator & when running node web servers. The background operator & will run the command line in the backgroud and so not tie up a command window; it is a feature borrowed from the UNIX shell. It means I can run several web servers or other long running (or permananent) executables from a single command window.

The other feature I want is the option to open a PowerShell command window from the context menu when in a Windows Explorer window. This already is working for my current version of PowerShell (5.1). I'd want it for PowerShell 7 as well.

It seems if you want the latest version of PowerShell, version 7, then you must deliberately install it. That is to say the Windows service packs and Windows updates did not upgrade my PowerShell from version 5.1 automatically. Here is the Microsoft web page for downloading and installing PowerShell 7.1.

The installer throws a series of dialog boxes which I have shown below, I took the defaults with the exception of the feature labelled Add 'Open here' context menus to Explorer. If I didn't take this option then I'd have to fiddle around in the Registry to get that feature working. Much better to turn on this feature at the install stage. The final screenshot shows the context menu feature working.

Multiple Background Jobs with Powershell

So now I am ready to run some instances of a node.js web server on different ports. Firstly, let me give some node.js source code. The following listing will return either Hello world or Bonjour le monde depending on the command line arguments on an ip address and port number also specified on the command line.

var args = process.argv.slice(2);

const http = require('http');

const hostname = args[0] || '127.0.0.1';
const port = args[1] || 3001;
const lang = args[2] || 'en';

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  var timeStamp = new Date().toISOString().replace(/T/, ' ').replace(/..+/, '');
  var greet = (lang ==='fr') ? 'Bonjour le monde de port': 'Hello world from port' ;
  res.end(`${greet} ${port} (${timeStamp})`);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/ language:${lang}`);
});

So to run the above I'd run the following example commands ...

node.exe .\server.js 127.0.0.2 3002 fr
node.exe .\server.js 127.0.0.3 3003 en

Below is a screenshot of PowerShell 7 where I run these commands with the ampersand & operator which forces them into the background. You can see that Powershell reports then as a background running job. These jobs can then be terminated using the stop-job command supplying the job number.

No comments:

Post a Comment