Category: Windows

Windows Administration Blog Archives, by Peter Whyte (Database Administrator).
Includes: Database Admin, Windows Admin, PowerShell, WSL & more…

  • Install Git on Windows

    Install Git on Windows

    This is a post on how to install Git (version control system) on a Windows computer.

    For more information have a look at the git-scm page, which is where we can download the client.

    There are a lot of configuration options throughout this wizard install, but there is no need to worry – most settings can be changed post-install, and in the worse case, reinstalling Git will not set you far back in life!


    Install Git on Windows (GUI)

    A simple download and wizard run; here are the notable configuration options throughout.

    Git Install Configure Extra Options

    Once the above is done, restart PowerShell / VS Code.

    Run ‘git –version’ in PowerShell to confirm.

    Open Git Bash from the Start Menu.

  • Create a Link Between Local Windows Files and WSL

    Create a Link Between Local Windows Files and WSL

    The ln command in Linux is used to create a link between files. This is useful for sharing files between your local machine and WSL.

    I’m linking to a ‘projects’ folder in this post but I get an error when cloning git repos in them (chmod error). Using mounted Windows drives for version-controlled projects is appearing to be a no-go.

    # Create a New Linked Folder
    # Remove a Linked Folder

    Create a New Linked Folder

    # Create sym link wsl
    ln -s /mnt/c/projects

    -s Create symbolic links instead of hard links.

    First I’m creating a local folder and then creating a link to the folder in my WSL home directory.

    PowerShell New-Item

    Next, I’m creating a new folder and file within WSL on the linked folder.

    Create Folder and File Linux

    And here’s the file created above shown within the local Windows environment.

    Folder and File in Windows Explorer

    Remove a Linked Folder

    List the files (-lai) to check for existing links ad then remove as your would a file (rm command).

    Remove Symlink

    We’re deleting the object visible to Linux here, not the folder in Windows.

  • Access Local Files from Windows Subsystem for Linux (WSL)

    Access Local Files from Windows Subsystem for Linux (WSL)

    Accessing local Windows files from a WSL distro can be achieved by navigating to the /mnt/c/ directory in your WSL Linux machine, or you can enter WSL from any Windows directory within a terminal.

    This post is to demo both methods described for accessing Windows files from WSL:
    # Navigate with cd /mnt/c/
    # Open WSL from PowerShell Terminal

    You can also create a symbolic link to create a new linked folder between your Windows computer and WSL. Check out my other blog post Create a Link Between Local Windows Files and WSL for more information.

    Navigate in Terminal to /mnt/c/

    When working within a WSL Linux environment, we can look at the files on our local Windows machine by navigating to the /mnt/ directory as shown in the example below.

    # navigate to home (wsl) linux folder
    cd ~
    
    # navigate c:\temp folder on local windows computer
    cd /mnt/c/temp
    WSL access Windows Files

    In the Windows Terminal above we are checking the contents of /mnt/ which is the local C & D volumes, and a folder named WSL.

    Open WSL from PowerShell Terminal

    When working within a PowerShell Terminal, we can open WSL from any Windows directory and the default Linux distribution will be opened with that local Windows-mounted path.

    In the example below we’re creating a new folder on Windows within a PowerShell Terminal, navigating into the new folder and then entering WSL.

    PowerShell Terminal Open WSL

    The PowerShell colours are difficult to see on that path, but it shows the new folder we created within Ubuntu WSL.

  • Reinstalling a WSL Disto

    Reinstalling a WSL Disto

    This post is a guide on how to reinstall WSL (Windows Subsystem for Linux) via command. This may be useful if you are looking to clear down and start a up fresh WSL instance, treating it as a throw-away environment. You should have any WIP code backed up to Git before running this.

    To remove a WSL distribution and its data, run wsl --unregister <distro-name>, amend the statement with the name of the distribution, which you can see by running wsl -l.

    You can also uninstall each of your WSL Linux distro apps on your machine via the Microsoft Store. This blog post shows examples of the command-line way.

    The following is included here:
    # List Installed WSL Distros
    # Uninstall a WSL Distro
    # Install Ubuntu on WSL

    List Installed WSL Distros

    We need to know the WSL distribution name which we want to remove. Run the following to show the currently installed Linux Distributions on your system:

    wsl -l
    

    Unregister/Uninstall a WSL Distro

    Caution: Once unregistered, all data, settings, and software associated with that distribution will be permanently lost. Reinstalling from the store will install a clean copy of the distribution. (MS Docs).

    The following command will uninstall a WSL Distro:

    wsl --unregister <distro-name>
    

    Install Ubuntu WSL

    My previous blog post covers installing Ubuntu 20.04 on WSL. It includes how to install Ubuntu via command or the Microsoft Store.

    We run the .exe file when doing this via command, entering the username/password details when prompted.

  • Enable Windows Subsystem for Linux (with Ubuntu 18.04)

    Enable Windows Subsystem for Linux (with Ubuntu 18.04)

    WSL allows Windows users to develop and run applications within a GNU/Linux environment. Previous to this feature release we needed VM’s or a dual boot setup.

    For more information, as always have a look at the Microsoft Docs. There’s a huge amount of tutorials and documentation on this area.

    This post is a simple guide and includes:
    # Enabling Windows Subsystem for Linux (WSL)
    # Downloading a Linux Distro
    # Installing a Linux Distro


    Enabling Windows Subsystem for Linux (WSL)

    Open PowerShell as Administrator and run the following to enable WSL:

    Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
    PowerShell Enable WSL

    You’ll then be prompted to restart your local computer.

    PowerShell Enable WSL Restart Prompt

    Downloading a Linux Distro

    You can find all the Linux Distributions on the Microsoft Store and download from there. This may be restricted by Group Policy if you’re on a Domain, so you can download manually from this list on the documentation page.

    For this guide I’m downloading using Invoke-WebRequest:

    cd c:\your_download_folder
    Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1804 -OutFile Ubuntu1804.appx -UseBasicParsing
    PowerShell Invoke-WebRequest Ubuntu 18.04

    Installing a Linux Distro

    We have to rename the .appx file I downloaded above to .zip, decompress and then run the .exe file to install Ubuntu.

    Rename-Item .\ubuntu1804.appx .\ubuntu1804.zip
    Expand-Archive .\ubuntu1804.zip .\ubuntu1804
    .\ubuntu1804\ubuntu1804.exe
    WSL Ubuntu Install

    The terminal should scope into the Linux instance. Type ‘exit’ to get back to PowerShell.


  • Creating a Linked Server with a MySQL Database

    Creating a Linked Server with a MySQL Database

    This is my 3rd Linked Server demo post, and this time it’s to a MySQL database.

    Noteworthy weblinks:
    # My Linked Server Blog Posts.
    # Microsoft Docs – Linked Servers.

    Here is a simple diagram of the setup in this post.

    The above was setup similar to what’s included in some of my previous posts:
    # Install SQL Server on Windows.
    # Install MySQL on Windows.
    # Test Connectivity to Remote Servers.

    Once the above is done, this post runs through the following steps to get a Linked Server configured:

    MySQL
    # Create MySQL Linked Server Login.
    SQL Server
    # Configure ODBC Data Source Settings.
    # Create a Linked Server to a MySQL Database.


    Create Linked Server Login on MySQL

    As always, this kind of task can be done using a management tool like MySQL WorkBench or via command.

    First up, I’ll get connected to MySQL via CLI.

    CREATE USER and then GRANTING SELECT capabilities for all tables* within a ‘milk’ database.  The first SQL steps here for me are to create the test database & table.

    -- Create test database & table
    CREATE DATABASE milk;
    USE milk;
    CREATE TABLE animal (id INT, type VARCHAR(50), breed VARCHAR(50), age DATE);
    INSERT INTO animal (1,'cow','white with black spots','2009-10-06');
    INSERT INTO animal VALUES (2,'cow','black with white spots','2011-12-16');
    
    -- Create Linked Server user
    CREATE USER 'linked_server_sql1'@'172.31.1.%' IDENTIFIED BY 'eCh0Ch4rl1E';
    GRANT SELECT ON milk.* TO 'linked_server_sql1'@'172.31.1.%';

    My connections are within the 172.31.1.0 network, so I’m adding in a wildcard (%) for all addresses on this range to be allowed to connect with this login.

    If I want to test this new MySQL login locally, I can create the user using ‘localhost’ too. Below I’m opening the mysql.exe file rather than using the MySQL Command Line Client application which logs in as root.

    Put on the User hat and do what you need to do.

    I only wanted read-only access, which I can confirm with a quick write test.

    That’s our Linked Server MySQL login ready!

    The above can also be done with a tool like MySQL WorkBench too; run the same commands above in a query window or via the Users and Privileges window. The new user account below would be able to connect from any host address.


    Configure ODBC Data Source Settings

    The MySQL ODBC driver download can be found here. Download & install on the SQL Server host machine.

    Note; at the time of writing this the most recent MySQL ODBC Driver version is 8.0.20. I’ve had to install version 8.0.18 as the 2 most recent versions were showing an error message on install.

    Run ODBC Data Sources as Administrator.

    Click into the System DSN tab and click Add.

    Select the MySQL ODBC Unicode driver.

    Enter all details required as shown. If you can see the database names the connection is all good so click OK.


    Create Linked Server to a MySQL Database

    Within SSMS; expand Server Objects, right-click Linked Servers and select New Linked Server.

    The Linked server name at the top of the next window is what you’ll need to include in queries, so choose that wisely.

    Then choose a provider for ODBC and enter the Data Source name which you named within the ODBC driver settings above.

    Enter the MySQL login details as created above within this post.

    I’m leaving all Server Options as defaults.

    Before I hit OK I’m scripting this out to code.

    USE [master]
    GO
    EXEC master.dbo.sp_addlinkedserver 
    	@server = N'MYSQL_SERVER_1', 
    	@srvproduct=N'', 
    	@provider=N'MSDASQL', 
    	@datasrc=N'MySQL_Linked_Server'
    
    USE [master]
    GO
    EXEC master.dbo.sp_addlinkedsrvlogin 
    	@rmtsrvname = N'MYSQL_SERVER_1', 
    	@locallogin = NULL , 
    	@useself = N'False', 
    	@rmtuser = N'linked_server_sql1', 
    	@rmtpassword = N'eCh0Ch4rl1E'
    GO

    When ready, take a breath, then hit OK or execute the SQL.

    Have a look in the SSMS Object Explorer to view the new Linked Server. We should be able to drill into the database & objects we have permission to.

    Now run queries to our MySQL Server using OPENQUERY.


  • “Changing the Primary Domain DNS Name of this Computer Failed” – Server 2008 R2

    “Changing the Primary Domain DNS Name of this Computer Failed” – Server 2008 R2

    Within an AWS account I have a Windows Server 2016 Domain Controller, and I’m trying to join a Windows Server 2008 R2 to my Whyte.net Domain.

    I get this error:

    Changing the Primary Domain DNS name of this computer to “” failed. The name will remain “whyte.net”.
    The error was:
    The specified server cannot perform the requested operation.

    I’ve run some domain checks which all appear to be successful. All traffic open between each server.

    Nothing of note shows in the Event Viewer…

    This isn’t something you should have to be doing, joining a now un-supported Windows Server to a domain. To help plan for this kind of change, have a look at Microsoft Docs – AD Functional Levels.


  • Testing Connectivity to Remote Server Ports with PowerShell

    Testing Connectivity to Remote Server Ports with PowerShell

    All admins need a tool to test connectivity to remote servers on TCP ports. In Windows, this is commonly done using PuTTy or PowerShell.

    This post is a note on my favourite way of testing remote TCP connections in Windows, which is using PowerShell:
    # Check a Port is Open (Pre Win08/Svr2012)
    # Check a Port is Open (Test-NetConnection)
    # Troubleshooting Remote Ports

    Important ports to remember in the life of a DBA may include:
    # SQL Server (1433)
    # RedShift (5439)
    # PostgreSQL (5432)
    # MySQL (3306)
    # Oracle (1521)

    Check a Port is Open (Pre Win08/Svr2012)

    This is for when you’re on a legacy server running an old version of PowerShell. I managed to spawn a Windows Server 2008 R2 box from the AWS Marketplace for this demo.

    # Check a port is open (pre Win08/Svr2012)
    $Ipaddress= Read-Host "Enter the IP address:"
    $Port= Read-host "Enter the port number to access:"
    $t = New-Object Net.Sockets.TcpClient
    $t.Connect($Ipaddress,$Port)
    if($t.Connected)
        {"Port $Port is operational."}
    else {"Port $Port is closed."}

    Enter IP address and port number when prompted.  

    Test-NetConnection PowerShell

    Below is an example of no connectivity, it’s failing to connect on port 1433. The server I’m testing does not have SQL Server installed, so there was nothing listening on that port.

    TCP Port Test PowerShell

    Check a Port is Open (Test-NetConnection)

    I’ve used Test-NetConnection frequently for years. It’s built-in to recent Editions of Window Server and is easier to use. We can also use ‘tnc’ as displayed in the example code below.

    # Test remote port is open
    Test-NetConnection -ComputerName lab-sql1.whyte.net -Port 1433
    
    # Same as above command using alternative syntax/ip
    tnc 172.31.18.100 -port 1433
    Test-NetConnection

    We can see from the screenshot above this test passed as TcpTestSucceeded came back true.

    Note:
    The traffic between you and another server may be flowing through various components that can include; local/internal/external firewalls, NAT Gateways, Security Groups/NACLs, load balancers & more.
    Diagnosing connectivity issues can be very complex. This is a simple test and might not be reflected in certain network traffic logs – if you’re troubleshooting maybe run your second port test with Putty.

    Troubleshooting Remote Ports

    If connectivity is failing, a few things to check may include:
    # There has to be something ‘listening’ on the remote server port.
    # Network (Inc. DNS) configurations & Security Groups.
    # Firewalls (at the Infrastructure level or local host config).

  • Forcing Encryption in SQL Server

    Forcing Encryption in SQL Server

    If you’re ever planning to allow external connections to a SQL Server, one of the first things to ensure is that the data is encrypted at rest and in transit.

    SQL Server has an option where we can force all connections on a SQL Server to be encrypted, which ensures us that we’re achieving encryption for our SQL connectivity.

    This post follows Microsoft Docs – Enable Encrypted Connections to the Database engine. It’s quite a complex piece so a full read of this would be necessary before planning this change.

    # Create Certificate (PowerShell)
    # Import PK to Trusted Root Certificates
    # Import Certificate into SQL Server
    # Force Encryption in SQL Server
    # Verify SQL Server Connectivity is Encrypted


    Create Certificate (PowerShell)

    The certificate must be issued for Server Authentication. The name of the certificate must be the fully qualified domain name (FQDN) of the computer.

    The above is a little note in amongst a bunch of pertinent info, found here; Microsoft Docs – Enable Encrypted Connections – Remarks

    I’m using a New-SelfSignedCertificate for this tutorial and creating it with PowerShell.

    Before running the following PowerShell script, amend .pfk output file location & DNS Names.

    New-SelfSignedCertificate -DnsName lab-sql1.whyte.net -CertStoreLocation cert:\LocalMachine\My -FriendlyName lab-sql1-cert -KeySpec KeyExchange -NotAfter (get-date).AddYears(99)
    $thumbprint = $(Get-ChildItem Cert:\LocalMachine\My).thumbprint
    $Pwd = ConvertTo-SecureString -String "Str0ngePassword1!" -Force -AsPlainText
    Export-PfxCertificate -Cert "Cert:\LocalMachine\My\$thumbprint" -FilePath "C:\temp_certificates\lab-sql1pk.pfx" -Password $Pwd -Force
    PowerShell New-SelfSignedCertificate
    Certificate File Windows Explorer

    Import PK to Trusted Root Certificates

    Open MMC and add the Certificates (Local Computer) Snap-in.

    MMC Local Computer
    MMC Console

    Expand Trusted Root Certification Authorities, right-click & select All Tasks > Import…

    Trusted Root Certificate Import

    Navigate to the .pfx file.

    Import pfx File

    Enter a password & continue.

    Private Key Password

    Finish up the wizard.

    Certificate Import Wizard
    Certificate Import Wizard

    Have a look at the new certificate within MMC.

    MMC

    Import Certificate into SQL Server

    Open SQL Server Configuration Manager, then right-click Protocols for MSSQLSERVER and select Properties.

    SQL Server Protocols

    Open the Certificate tab and you should be able to view & select the new certificate from the drop-down menu.

    Click to Apply & Ok out of the window – I’m doing the Forcing of Encryption separate (below).

    Protocols for MSSQLSERVER

    You’ll get this prompt.

    Any changes made will be saved, however, they will not take effect until the service is stopped and restarted

    Restart the SQL Services from the configuration manager. If your services don’t start back up again, then ensure the service accounts have the appropriate permissions. For this demo, my AD Service Accounts are members of the local Administrators group.  

    SQL Server Configuration Manager

    Force Encryption in SQL Server

    Right click Protocols for MSSQLSERVER, select Properties and within the Flags tab enable the Force Encryption option.

    SQL Server Force Encryption

    Restart the SQL Services.

    SQL Server Service Restart

    Verify SQL Server Connectivity is Encrypted

    Open a local and/or remote query session. You may have to ensure the Encrypt connection & Trust server certificate options are checked.

    SSMS Connection Properties

    Now query sys.dm_exec_connections to check the encryption_option of all SQL connections.

    SELECT * FROM sys.dm_exec_connections
    sys.dm_exec_connections
  • Running PowerShell Scripts as Scheduled Tasks in Windows

    Running PowerShell Scripts as Scheduled Tasks in Windows

    When you need something scheduled in Windows, the Task Scheduler is the tool at-hand.

    Running PowerShell (.ps1) scripts as Scheduled Tasks is done differently than differently than running regular .bat scripts. Sometimes I forget how it’s done, so a worthy enough post.

    Below I’m creating a daily reboot by calling PowerShell script in Task Scheduler on Windows Server 2016.


    Create Scheduled Task to Trigger a PowerShell Script

    1. Open Task Scheduler.

    Task Scheduler New Task

    2. Right-click and Create New Task.

    New Scheduled Task General Tab

    I’ve given it a Name and Description here. In work-life, I’d usually be running these sort of jobs with an AD service account. As well as that, if you’re running a local only PowerShell script then we don’t need to store the password as per the Security options above.

    3. Create a schedule within the Triggers tab.

    Scheduled Task Triggers Tab

    Remember, we can set schedules on many things (e.g. Windows Events or when the server is Idle).  

    4. Create a new Action within the next tab. PowerShell scripts require the {powershell} program name as shown, as well as the {-File “C:\Temp\powershell_script.ps1} argument.

    Scheduled Task Edit Action
    Scheduled Task Actions Tab

    5. Next, configure Conditions & Settings – read through what suits your job. The only thing I’ve changed is for it to stop if the task runs longer than 1 hour.

    Scheduled Task Settings Tab

    6. Finally, verify it’s working by losing connectivity!

    PowerShell Scheduled Task Daily Reboot