Tag: Windows Admin

  • PowerShell Create Folder If Not Exists

    PowerShell Create Folder If Not Exists

    In this post, I share a script that will help you create folders and sub-folders with PowerShell if they do not already exist. We use Test-Path in our PS scripts to check if objects exist before executing the create command.

    This is one small part of a more detailed blog post I have on creating files and folders using PowerShell. My other post, How to Create New Files & Folders in PowerShell also covers more details on the differences between creating files vs creating folders.

    Create New Folder (if not exists) in PowerShell

    We’re creating a new folder, only if it doesn’t already exist – “C:\temp\demo”

    The create folder command is New-Item, which runs conditionally depending on the Test-Path true/false result. When we run this script it also creates your C:\temp directory if it doesn’t already exist.

    # create folder if not exists .ps1
    $path = "c:\temp\demo"
    If(!(Test-Path $path) ){
        New-Item -ItemType Directory -Force -Path $path
    }

  • How to Create New Files & Folders in PowerShell

    How to Create New Files & Folders in PowerShell

    This is a post on how to create new files and folders using PowerShell.

    Creating new files and folders in Windows is generally done via GUI. That’s what it’s there for, the simplicity. But when you’re scripting or doing admin work, you might want to create new files and folders via command.

    This guide covers performing the following in your PowerShell Terminal –

    # PowerShell: Create a New Folder
    # PowerShell: Create a New File
    # PowerShell: Create New Folder (if not exists)

    Create New Folder in Powershell

    New-Item is the command to create the new folder and item. We just need to amend the ItemType to be a Directory for us to create a folder.

    # create new folder in powershell
    New-Item -ItemType Directory -Name Test_Stuff
    PowerShell New-Item Directory

    Create New File in PowerShell

    As mentioned above, it’s the same command, New-Item, and we’re changing the ItemType to File this time.

    # create new file in powershell
    New-Item -ItemType File -Name Test_File.txt
    PowerShell New-Item File

    Further reading: We also can add text to this file by using Add-Content & Get-Content (to view content).

    Create New Folder (if not exists) in PowerShell

    This time, it’s a script rather than a one-liner/cmdlet.

    We’re only creating a new folder only if it doesn’t already exist – “C:\temp\demo”

    When we run this script it also creates the C:\temp directory if it doesn’t already exist.

    The create folder command is New-Item, which runs conditionally depending on the Test-Path true/false result.

    # create folder if not exists
    $path = "c:\temp\demo"
    If(!(Test-Path $path) ){
        New-Item -ItemType Directory -Force -Path $path
    }
    PowerShell Create Folder if not exists
  • “.ps1 cannot be loaded because running scripts is disabled on this system” PowerShell Error

    “.ps1 cannot be loaded because running scripts is disabled on this system” PowerShell Error

    When attempting to run a PowerShell script you may receive the following error:

    cdk.ps1 cannot be loaded because running scripts is disabled on this system.
    For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170

    cannot be loaded because running scripts is disabled on this system

    This post is here to help you resolve this issue. The reason this is happening is due to the default ExecutionPolicy not allowing this action. We need to change it from Undefined to RemoteSigned or Unrestricted.

    Resolution: Set Execution Policy to RemoteSigned

    To resolve this “script cannot be loaded because running scripts is disabled on this system” error message:

    1. Open PowerShell as Administrator.

    2. Check current Execution Policies: Run Get-ExecutionPolicy

    Get-ExecutionPolicy -List

    3. Amend Local Execution Policy: Run Set-ExecutionPolicy.

    Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned
    Set-ExecutionPolicy PowerShell

    All should work fine after the above.

    Last updated: 29/09/2022

  • 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).

  • 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

  • Domain Join Sanity Checks

    Domain Join Sanity Checks

    In order to join a Windows Server to a domain, you may need to request that the network team open certain firewall rules. The network requirements for this process can be complex and may vary depending on your specific environment.

    After joining a domain, especially in a new environment, it is important to perform some checks to ensure everything is working correctly. These checks may include using GPResult and GPUpdate to update and verify Computer and User Policies, using Nltest to perform network administrative tasks such as querying domain controllers and trust relationships, and reviewing the Windows Event Viewer for any issues.

    This post shows examples of performing such checks post joining a Domain for a Windows Server:
    # GPResult / GPUpdate
    # Nltest
    # Windows Event Viewer

    GPUpdate / GPResult

    After joining a Windows Server to a domain, you can use the gpupdate command to check if the domain join is healthy. This command updates Computer and User Policies on the server, and can help to ensure that the server is properly configured and communicating with the domain controller.

    Here is an example of running gpupdate:

    Windows Server GPUpdate

    We can also have a look at applied Computer policies using the /v parameter when running gpresult.

    Windows Update GPResult

    Nltest

    Nltest.exe is a command-line tool that allows you to perform network administrative tasks, including querying and testing the status of domain controllers and trust relationships. Some examples of the tasks that you can perform with Nltest include:

    nltest /dclist:<domain> lists all the domain controllers in the domain.

    nltest dclist

    nltest /dsgetdc:<domain> queries DNS and returns a list of domain controllers (with IPs).

    nltest dsgetdc

    nltest /dsgetsite returns the site name of the domain controller.

    nltest getsite

    nltest /sc_query:<domain> reports the state of the secure channel for when it was last used.

    nltest scquery

    Windows Event Viewer

    The Windows Event Viewer is a useful tool for viewing and managing events that are recorded by Windows operating systems. While not all events recorded in the Event Viewer require investigation, it is important to pay attention to errors and critical events, especially during the domain join process.

    Windows Event Viewer

  • Configuring Windows Server Core

    Configuring Windows Server Core

    Windows Server Core is the CLI only version of the Windows OS. This post is a run-through of configuring a new Windows Server 2016 Core host, detailed in the following steps;

    # Installing Windows Server 2016 Core.
    # (CLI) Changing a Windows Server Hostname.
    # (CLI) Amending TCP/IP & DNS Settings.
    # (CLI) Joining a Windows Server to a Domain.


    Installing Windows Server 2016 Core

    When installing Windows Server, we need to select the following option.  

    Windows Server Core Install

    Once the above is done and the reboot happens, the following will appear.

    Server Core Enter Admin Password

    Enter the Administrator password…

    Server Core Enter Admin Password

    We’re now logged in and ready to go.

    PowerShell Get-Hostname

    Changing a Windows Server Hostname

    An easy task done with the Rename-Computer cmdlet accepted by PowerShell, followed by a reboot.

    PowerShell Rename-Computer

    Amending TCP/IP & DNS Settings

    First we need to look at the current recognised interfaces using the Get-NetIPConfiguration cmtlet.

    PowerShell Get-NetIPConfiguration

    Then set a new private IP address using the New-NetIPAddress cmdlet.

    PowerShell New-NetIPAddress

    Lastly, set the DNS address using Set-DnsClientServerAddress.

    PowerShell Set-DNSClientServerAddress

    The private IPv4 network has been configured, now we should verify we have line-of-sight.

    Ping IP Test
    Ping Hostname Test

    Joining a Windows Server to a Domain

    To join a Windows OS to the domain, we can use the Add-Computer cmtlet – You’ll immediately be prompted for authorisation from an account that can join computers to the domain.  

    PowerShell Add-Computer

    Enter the Domain Name.

    PowerShell Add Computer Domain Name

    Reboot once done.

    PowerShell Add-Computer Reboot

    When the box is up, you’ll have the option to login with the Local Administrator account, or with another user.

    Server Core Login Other User

    If selecting Other user, you’ll have an entry for the domain you’re signing into.

    Server Core Domain Login
    Server Core Hostname and Login Info

  • Joining a Windows Host to a Domain

    Joining a Windows Host to a Domain

    This post contains a demo of joining a Windows Server onto a test Domain, which I created in my previous post (Installing Active Directory on Windows Server 2016).

    Joining a Windows Computer to Active Directory Domain Services is required in 99% of Corporate environments, and is usually a Systems Administrator task to configure at the Domain Controller side. Adding a computer to AD allows your computer to be administered via Group Policies that can be applied to all remote computers globally within your company. This helps companies lock down computers and roll out new software or updates.

    There are 2 parts to this one:
    # Creating a New Domain User Account
    # Joining a Windows Server to a Domain

    Creating a New Domain User Account

    I’m creating a new user account for me to carry out all changes required to set up my lab. It’ll be a new OU in AD, create a new user account and then add it to the Domain Admin group.

    1. Right-click the Domain Name within Active Directory Users and Computers, select New and Organisational Unit:

    Active Directory New Organisational Unit

    2. Enter the new OU name – I’m going to pretend I’m in the IT Department:

    Active Directory New Organisational Unit Name

    3. Within the IT OU, right-click and select New-User:

    Active Directory New User

    4. Enter new user details:

    Active Directory New User Details

    5. Enter password stuff:

    Active Directory New User Password

    6. Finish:

    Active Directory New User Finish

    7. Right-click the new user and select Add to a group:

    Active Directory Add User to Group

    8. Enter king group, Domain Admins:

    Active Directory Add User to Domain Admins

    Joining a Windows Server to a Domain

    1. First, I have to get onto the same private IP range as the DC:

    IPv4 Config
    Ping Test to Active Directory

    2. Within Server Manager, click the Computer name link:

    Windows Server Manager Computer Name

    3. Click Change:

    Windows Systems Properties

    4. Amend the hostname and enter the Domain name:

    Computer Name Change and Join Domain

    5. Enter credentials for an account that can join the domain (the account created above within this post would also work):

    Domain Join Elevation Prompt

    6. When the server next boots up a domain user account can log in:

    Windows Server Login to New Domain

    And that should be us!

  • Installing Active Directory on Windows Server 2016

    Installing Active Directory on Windows Server 2016

    This post contains a demo installation of Active Directory Domain Services on Windows Server 2016. It follows a previous post for a series of test lab configuration posts.

    Microsoft docs on installing AD on Windows Server can be found here: Install Active Directory Domain Services

    Configuring a Windows Server 2016 on a local Hyper-V can be done by following my previous post: Installing Windows Server 2016 with Hyper-V

    The following steps will get your test Windows Server environment set up to run Active Directory:
    # Create a Hyper-V Private Network.
    # Configure Windows TCP/IP Settings.
    # Rename the Windows Server Host.
    # Install Active Directory.
    # Promote the Server to a Domain Controller.
    Once the above has been achieved, you can create a new VM in Hyper-V (or other Hypervisor) and join your Domain, as I’ve done for some tests.

    Create a Hyper-V Private Network

    1. Right-click the Hyper-V host and select Virtual Switch Manager.

    Hyper V Virtual Switch Manager

    2. Select Private and Create Virtual Switch.

    Hyper-V VSwitch Manager New Private Switch

    3. Enter a name for the network and click okay.

    HyperV vSwitch Manager

    4. Right-click the VM in Hyper-V and click Settings.

    HyperV VM Settings

    5. Add a new Network Adapter.

    HyperV Add New Network Adapter

    6. Select Private vSwitch as named above and click OK.

    HyperV Add New Network Adapter

    Configure Windows TCP/IP Settings

    1. When the above has been set-up, Windows Server will show network settings as Identifying…

    Windows Server Identifying Network

    2. Right-click the network icon and click Open Network and Sharing Center.

    Windows Network and Sharing Center

    3. Click the highlighted active Ethernet connection.

    Windows Server Network and Sharing Center

    4. Open Properties.

    Windows Ethernet Adapter

    5. Open Internet Protocol Version 4 (TCP/IPv4) Properties.

    Ethernet Adapter IPv4 Properties

    6. Enter IP and subnet addresses.

    Windows Ethernet Adapter IPv4 Address

    Rename the Windows Server Host

    1. Open Server Manager and click the highlighted Computer Name.

    Windows Server Manager Host Info

    2. Click Change…

    Windows System Properties

    3. Enter new Computer Name and click OK.

    Windows Server Computer Rename

    The host will require a reboot once done.

    Installing Active Directory

    1. Within Server Manager, click Manage > Add Roles and Features.

    Windows Server Manager Add Roles and Features

    2. Before you begin, read the before you begin.

    Server Manager Add Roles and Features

    3. Select Role or Feature-based installation.

    Server Manager Add Roles and Features Installation Type

    4. Select the destination server.  

    Server Manager Add Roles and Features Destination Server

    5. Tick the Active Directory Domain Services checkbox.

    Server Manager Add Roles

    6. The following will appear – click to add the additional tools.

    Server Manager Add Roles Active Directory

    7. No features are being added at this time – click to continue.

    Server Manager Add Features

    8. ADDS page is worth a read – nothing to change here.

    Server Manager AD DS

    9. Review and click to install.

    Server Manager Roles and Features Installation

    10. Leave it a few minutes and we’re then able to promote this server as a new Domain Controller.

    Server Manager Active Directory Installation

    Promote the Server to a Domain Controller

    1. Once done with the above, there won’t be a finish point within the wizard. Click the flag on Server Manager to Promote the server to a Domain Controller.

    Active Directory Promote to DC

    2. This is a new test environment, so I need to Add a new forest.

    Active Directory Domain Services Config Wizard

    3. A new Forest means Functional Levels can be the latest edition available, Windows Server 2016. This is also the place to enter an important password that is required if recovering a failing AD.

    Active Directory Domain Controller Options on Install

    4. The following error is listed within the known issues for installing and removing AD DS. It’s expected if create a new forest as I’m doing.

    Active Directory Domain DNS Options

    5. Enter a preferred NetBIOS name.

    Active Directory Configuration Additional Options

    6. Locations can stay as defaults of course.

    Active Directory Installation Paths

    7. Time for us to review wizard selections.

    Active Directory Installation Review

    8. As you’ll see in the image above, we can click to view the PowerShell script that is about to run with the wizard selections included.

    Active Directory Installation Script

    9. A prerequisites check will run as we hit next from above. 

    Active Directory Installation Prerequisites

    10. Click to install…

    Active Directory Installation Progress

    11. An automatic reboot will be initiated at the end.

    Windows Reboot

    12. When back up and running, we can log in to the new domain.

    Windows Server Domain Login

    13. And have a look at our Active Directory Users & Computers, just for the fun demo of course.

    dsa.msc
    Active Directory Users and Computers
  • Installing Windows Server 2016 with Hyper-V

    Installing Windows Server 2016 with Hyper-V

    This post contains a demo of installing the Windows Server 2016 Operating System on Hyper-V.

    To install the Hyper-V Role on Windows 10, see this guide from Microsoft Docs: Install Hyper-V on Windows 10.

    There are two parts to this one:
    # Create a new Hyper-V Virtual Machine
    # Install Windows Server 2016

    Once you are done with this guide you will be logged into a new Windows Server on Hyper-V. You will then be ready to configure and run tests on your server. The next step for me would be to Install Active Directory (AD) on the server.

    Creating a new Hyper-V Virtual Machine

    1. Right-click your Hyper-V Manager host machine, and select New > Virtual Machine…

    Hyper-V New Virtual Machine
    New Virtual Machine HyperV

    2. Enter the name of the new VM and the location on disk.

    Hyper-V VM Name and Location

    3. Select Generation of VM.

    Hyper-V Virtual Machine Generation

    4. Enter the memory allocation amount.

    Hyper-V Virtual Machine Memory Allocation

    5. Select a network connection (I’ll set this up later).

    Hyper-V Virtual Machine Network

    6. Enter the dynamic virtual hard disk limit, and for this tutorial, I’m leaving the vHD location as default (driven from the previous selection).

    Hyper-V Virtual Machine Hard Disk

    7. Select an Operating System ISO file.

    Hyper-V Virtual Machine ISO

    8. Review configuration and hit finish.

    Hyper-V New Virtual Machine Summary

    9. Power up the new VM!

    Hyper-V Virtual Machines
    Hyper-V Virtual Machine List

    Installing Windows Server 2016

    1. Connect to the new VM (ensuring step 7 above was followed).

    Hyper-V VM without OS

    2. Hit any key.

    Hyper-V boot from CD

    3. After 30 seconds or so of loading, select your location.

    Windows Server 2016 Installation Language

    4. Click to start the Windows Server installation.

    Windows Server 2016 Installation

    5. GUI this time around, and Datacenter Edition for the test environment.

    Windows Server 2016 Datacenter Installation

    6. Accept the usual.

    Windows Server 2016 License Agreement

    7. Check advanced options.

    Windows Server 2016 Installation Type

    8. Install on the 50GB vHD.

    Windows Server 2016 Installation Location

    9. Hit next, and away it goes…

    Windows Server 2016 Install

    10. The installation will finish up and restart once it’s done. Before the Windows Server login screen is shown, the built-in administrator password needs to be set.

    Windows Server 2016 Admin Password

    11. Login with the above password.

    Windows Server 2016 Administrator Login

    12. Hurray, it’s Windows 2016 everybody!

    Windows Server 2016 Server Manager