top of page

59 items found for ""

  • Basic Ansible Setup for Windows

    Introduction to Ansible Welcome to this introduction to managing Windows from Ansible, unlike Microsoft's management solutions, it's free and agentless! Imagine a single tool that automates the setup, configuration, and maintenance of multiple Windows and Linux servers. With its simplicity, Ansible lets you easily orchestrate your server infrastructure. No more manual tasks, no more sleepless nights—just smooth sailing through the seas of automation. Well, it will allow those repetitive tasks to be automated at least. Aims for Ansible This article aims to offer straightforward guidance on configuring Ansible for the management of a non-domain joined Windows Server via the execution of remote tasks. Subsequent articles will expand upon this foundation by incorporating features such as Vault's password management, domain-joined servers, and Kerberos authentication. What you will need to download Latest Ubuntu Desktop Download ISO Visual Code for Linux Windows WinRM Configurator Script Ansible Documentation Ansible Host and Yaml Files Pick your Linux of Choice (Ubuntu Desktop) I'll be opting for my less preferred Linux distribution, Ubuntu Desktop. However, I find it to be the most user-friendly choice for Microsoft-focused engineers. Rocky Linux is a viable alternative, though its configuration might involve additional steps. I won't go into a detailed step-by-step installation of Linux, but simply download the ISO, mount it within your preferred VM solution and install, following the default setup. Some Sort of Virtualization or Cloud I'll be opting for Hyper-V as my preferred virtualization platform to host both Ubuntu and Windows Server 2022. Its seamless integration with both Windows Server and Windows 11 client eliminates any compatibility or migration concerns I may face moving images between the 2. There are two recommended Hyper-V configurations for Linux installation. Opt for a Generation 2 VM to enable Secure Boot capability, and within the Security section of the VM, select 'Microsoft UEFI Certificate Authority'. Post-deployment, run the following command from PowerShell, once the Linux VM is powered down, select the resolution that aligns best with your monitor. Set-VMVideo Ansible2 -horizontalresolution:1900 -verticalresolution:1200 -ResolutionType Single Update Ubuntu After successfully deploying Ubuntu, it is crucial to install any updates to ensure the smooth execution of future installations by running the following command from a shell terminal. sudo apt-get update -y && apt-get upgrade -y Install Ansible Ansible is installed with the following command. sudo apt-get install ansible -y List currently installed collections, as you will see there's support for OS, Cloud, Network devices and much more. ansible-galaxy collection list To update the Windows community collection that's installed by default. ansible-galaxy collection install To install the latest stable collection by Ansible, run the following ansible-galaxy collection install Before continuing type ip address in the terminal and record for later use. Install Microsoft's Visual Code for Linux To assist with writing Yaml and to minimise the moving of files Microsoft's Visual Code for Linux will be installed on Ubuntu. If you can't outdo them, it seems the strategy is to join them. Well played Microsoft. Instructions can be found @ for Ubuntu and other distro's. For Ubuntu follow the next set of instructions. sudo apt-get install wget gpg wget -qO- | gpg --dearmor > sudo install -D -o root -g root -m 644 /etc/apt/keyrings/ sudo sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/keyrings/] stable main" > /etc/apt/sources.list.d/vscode.list' rm -f sudo apt install apt-transport-https sudo apt-get update sudo apt-get install code Launch Visual Code once it's installed, then create a new directory in the Documents directory named Ansible. That concludes the installation and configuration of Ubuntu and Ansible. Now, let's proceed to the setup of Windows. WinRM and Windows Server Configuring Windows for remote management from Ansible is a little involved with instructions available from the Anisble website: Windows Setup Nevertheless, there exists a pre-configured script accessible on Github: Windows Anisble Configurator Script To get up and running with this basic implementation download the 'ConfigureRemotingForAnsible.ps1' and execute the script from PowerShell with Administrative rights. A cautionary note: the implemented configuration is open, granting remote WinRM access to any client. To address this, simply modify lines 417 and 423 by adding the specific remote IP of the Ansible server; in my case, it's This updates the firewall from allowing any address to that of the one specified. = Windows Server = Ubuntu\Ansible ln 417 netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 protocol=TCP action=allow remoteIP= ln 423 netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any remoteIP= To assess WinRM access from another Windows client, input the following commands in PowerShell. Remember to update the password and AnsibleIP with your system's information. In case the Windows Firewall imposes the above RemoteIP restriction, include the test client's IP in the 'Allow WinRM HTTPS' remote scope firewall rule. $username = "administrator" $password = ConvertTo-SecureString -String "ChangeMe1234" -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password $session_option = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck Invoke-Command -ComputerName AnisbleIP -UseSSL -ScriptBlock { ipconfig } -Credential $cred -SessionOption $session_option Confirm that the WinRM Service is running. Get-Service WinRM If the WinRM service isn't started execute the following to set the service to automatic and start. Set-Service -Name WinRM -StartupType Automatic -ErrorAction SilentlyContinue Get-Service -Name WinRM | Start-Service To get the WinRM configuration execute the following: winrm enumerate winrm/config/listener Listener Address = * Transport = HTTP Port = 5985 Hostname Enabled = true URLPrefix = wsman CertificateThumbprint ListeningOn =,, ::1, fe80::a81e:3b96:6d3b:3d6c%3 Listener Address = * Transport = HTTPS Port = 5986 Hostname = WIN-JE1B7QU8B8R Enabled = true URLPrefix = wsman CertificateThumbprint = FC24D87A798ECA4EA8BF4EE0C8CD7FD2CC51A67C ListeningOn =,, ::1, fe80::a81e:3b96:6d3b:3d6c%3 Ansible Environment In Ansible, host files and YAML are crucial in defining and organizing the infrastructure you intend to manage. Host Files: A host file in Ansible is where you specify the details of the servers or systems you want to manage. It typically includes information like IP addresses, hostnames, and grouping of hosts based on certain criteria (e.g., development, production). Host files help Ansible understand the inventory of systems it can control, making it an essential component for playbook execution. Without Ansible Vault passwords are hardcoded and clear text within the Hosts file. Vault will be covered in a subsequent article. [Windows] [Windows: vars] ansible_user=administrator ansible_password="ChangeMe1234" ansible_connection=winrm ansible_winrm_scheme=https ansible_port=5986 ansible_winrm_server_cert_validation=ignore ansible_kerberos_delegation=false YAML (YAML Ain't Markup Language): YAML is a human-readable data serialization format often used for configuration files and data exchange between languages with different data structures. In Ansible, YAML is used to write playbooks, which are scripts that define the tasks to be executed on the managed hosts. It uses indentation to represent data hierarchy, making it easy to read. Writing can present a bit of a challenge as its hierarchal nature requires the structure to be indented and spaced correctly. In this example, the contents from the Ansible directory are copied to the targeted Windows Administrator's Desktop. --- - name: Copy hosts: Windows become: false gather_facts: false vars: source: "/home/user/Documents/Ansible" destination: "Desktop/" tasks: - name: copy ping src: "{{ source }}" dest: "{{ destination }}" Host and YAML files play a crucial role in making Ansible configurations clear, structured, and easy to manage. Host files define the inventory, while YAML defines the tasks and configurations to be applied to the hosts. Host File and Initial Test Ensure you're logged on to Ubuntu\Ansible and launch Visual Code. Navigate to '/home/user/Documents/Ansible' and create a file named 'hosts.ini. Taking the above host file as an example, incorporate the necessary details that match your Windows system and save the file. Or download the examples provided: Let's create the most basic ping test to confirm access to Windows, create a file named 'ping.yml' and insert the following. --- - name: Ping Windows Test hosts: Windows gather_facts: false tasks: - name: Ping targets win_ping: Launch a shell and CD to '/home/user/Documents/Ansible'. Type and execute the following command ansible-playbook -i hosts.ini ping.yml Kudos on acing the Ansible setup for managing Windows! File Copies To and Fro Before delving into the YAML file, it's essential to acquaint yourself with the following path rules. The Windows path rules should be written in the following format. Good tempdir=C:\\Windows\\Temp Works tempdir='C:\\Windows\\Temp' tempdir="C:\\Windows\\Temp" Bad, but sometimes works tempdir=C:\Windows\Temp tempdir='C:\Windows\Temp' tempdir="C:\Windows\Temp" tempdir=C:/Windows/Temp Fails tempdir=C:\Windows\temp tempdir='C:\Windows\temp' tempdir="C:\Windows\temp" Copies the contents of the Ansible directory to the Desktop of the target Windows server. --- - name: Copy hosts: Windows become: false gather_facts: false vars: source: "/home/user/Documents/Ansible" destination: "Desktop/" tasks: - name: copy ping src: "{{ source }}" dest: "{{ destination }}" Copies a named file from the Windows Desktop up to the Ansible directory using 'fetch'. --- - name: Copy hosts: Windows become: false become_user: false gather_facts: false vars: source: "Desktop/test1.txt" destination: "/home/user/Documents/Ansible/test1.txt" tasks: - name: copy ping ansible.builtin.fetch: src: "{{ source }}" dest: "{{ destination }}" Further guidelines can be found @ Basic Commands This concludes the introduction by running a command line on the designated Windows server and saving the results to a text file. --- - name: cmds hosts: Windows become: false gather_facts: false tasks: - name: some cmd win_command: cmd.exe /c whoami.exe > "Desktop\whoami.txt" - name: ipconfig win_command: cmd.exe /c ipconfig /all > "Desktop\ipconfig.txt" Finally Done! Thanks for your time reading this intro to managing Windows from Ansible. Creating each article demands time and effort, diverting me from other learning pursuits. Your comments and shares are highly valued and greatly appreciated. Finally a big shout-out to Harv for opening my eyes to a life beyond SCCM.

  • PowerShell Code Signing with a Self-Signed Certificate

    Hey PowerShell enthusiasts! Ever wondered how to beef up your script security? Not every system gets the luxury of a Certificate Authority (CA)? Imagine your scheduled management scripts getting messed around by that one admin who loves tinker or worse, some bad actors. Today, let's tackle that risk head-on! We're diving into the world of self-signed certificates and code signing to keep your scripts safe and sound. Creating self-signed certificates for PowerShell script validation involves generating digital certificates locally and without relying on a Certificate Authority (CA). Using PowerShell's New-SelfSignedCertificate cmdlet, parameters like Subject and KeyUsage are specified. This process allows script integrity through code signing. Once created, the certificate can be used to digitally sign scripts with the `Set-AuthenticodeSignature` cmdlet, providing a level of assurance about the script's legitimacy and origin. Self-signed certificates may lack third-party validation, they boost script security by mitigating the risks of unauthorized changes. Still, be cautious; mishandling self-signed certificates could introduce vulnerabilities. Properly document and securely distribute certificates to maintain signed PowerShell script integrity in controlled environments. This guide is geared towards Active Directory Domains lacking a CA and DevOps keen on signing their PowerShell scripts. Don't worry; we're all about good practices here! To get started, make sure you have an offline Windows Server for crafting your Self-Signed certificate, a Windows 11 client (not extensively tested, but should work), and a separate client for testing the signed scripts with Admin access for tweaking Group Policy and importing certificates into the local machine store. Less chat more script..... Certificate Server Here are the key snippets from the script – the ones that matter. The script is downloadable from Github. Declare working directories, either create the directories or allow the script to, not forgetting to add scripts that need signing to "C:\_PSScripts\". $certExport = "C:\_Certs\" $ScriptRepo = "C:\_PSScripts\" Set parameters. $params = @{ Subject = 'Self Signed PS Code Signing' DnsName = '' FriendlyName = 'Self Signed PS Code Signing' NotAfter = (Get-Date).AddYears(5) Type = 'CodeSigning' CertStoreLocation = 'cert:\CurrentUser\My' KeyUsage = 'DigitalSignature' KeyAlgorithm = 'RSA' KeyLength = 2048 HashAlgorithm = 'sha256' } Create a new self-signed certificate based on the above parameters and send the details to 'newCodeSigningCert' variable for reference later. New-SelfSignedCertificate @params -OutVariable newCodeSigningCert Export the public key to the file system. Export-Certificate -Cert "cert:\CurrentUser\My\$($newCodeSigningCert.Thumbprint)" -FilePath "$($certExport)\CodeSigning.cer" Re-import certificate into Trusted Root otherwise it's not possible to validate any signed scripts. Import-Certificate -FilePath "$($certExport)\CodeSigning.cer" -Cert Cert:\LocalMachine\root Sign all scripts in C:\_PSScripts using a Foreach loop $gtPSscripts = Get-ChildItem -Path $ScriptRepo -filter *.ps1 -Recurse -Force foreach ($PSscriptItem in $gtPSscripts) {Set-AuthenticodeSignature $PSscriptItem.fullname -Certificate (Get-ChildItem "cert:\CurrentUser\My\$($newCodeSigningCert.Thumbprint)" -CodeSigningCert)} And there you have it! Snag those signed scripts and the exported certificate (.cer), then copy them over to the test client. Easy peasy! Check out any of the signed scripts, and you'll spot a signature block appended to the script. # SIG # Begin signature block # MIIFrQYJKoZIhvcNAQcCoIIFnjCCBZoCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # vhJhRK4rqe9AhAcGnbPDQg37+EgaN93UzTn2YIOVmbFrQcOwQfDJEzzVOrkLKJdX # yjdMD070/gJajAELBJDoxsY= # SIG # End signature block Test the Signed Scripts on a Client Let's assume the freshly signed scripts and certificate file reside in the same directories. Now open PowerShell with admin rights and execute the following commands. Declare the working directories. $certExport = "C:\_Certs\" $ScriptRepo = "C:\_PSScripts\" Import the certificate into the Trusted Root LocalMachine Certificate store. Import-Certificate -FilePath "$($certExport)\CodeSigning.cer" -Cert Cert:\LocalMachine\root To prevent the following prompt: Do you want to run software from this untrusted publisher? File C:\_PSScripts\gwmi-signed.ps1 is published by CN=Self Signed PS Code Signing and is not trusted on your system. Only run scripts from trusted publishers. [V] Never run [D] Do not run [R] Run once [A] Always run [?] Help (default is "D"): A Import the certificate into the Trusted Publishers LocalMachine Certificate store to prevent any prompts when executing the scripts. Import-Certificate -FilePath "$($certExport)\CodeSigning.cer" -Cert Cert:\LocalMachine\AuthRoot Launch Group Policy Editor or gpedit.msc. Browse to Computer Configuration, Administrative Templates, Windows Components, Windows PowerShell Enable 'Turn on Script Execution', select 'Allow Only Signed Scritps' in the drop-down and click OK. Run 'gpupdate /force' to apply the settings. If your scripts have a digital signature using your own certificate, they'll run smoothly in PowerShell. But the ones that aren't signed won't work. Perfect Script Security... mostly. Scripts that are signed and then updated without re-signing won't run either and you'll receive the error below. .\gwmi-signed.ps1 .\gwmi-signed.ps1 : File C:\_PSScripts\gwmi-signed.ps1 cannot be loaded. The file C:\Certs\gwmi-signed.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy. Bypassing the Execution Policy from PowerShell isn't possible. Set-ExecutionPolicy -ExecutionPolicy Bypass Execution Policy Change The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective ReadMe: PowerShell_ISE doesn't impose any limitations or restrictions. Unlike other environments, it doesn't enforce the Execution Policy, allowing the execution of any script, whether signed or not. Keep it Secret, Keep it Safe A PFX certificate, also called PKCS#12 or P12, is a file format used for keeping and moving cryptographic stuff like private keys and their matching public key certificates. It provides a secure way to store and share these sensitive elements. A PFX file typically includes: Private Key Public Key Certificate Certificate Chain Password Protection Once you use the New-SelfSignedCertificate command, the resulting certificate comes with both the public and private keys and can be exported as a PFX file containing the private key – basically, the whole shebang. That's why it's crucial to keep the signing server offline and well-guarded. It's also a good idea to back up the certificate, just for safety or to migrate to another host. The following commands will do just that Create a secure string password. $CertPassword = ConvertTo-SecureString -String "ChangeME1234" -Force -AsPlainText Export the private key as a pfx and password protect. Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($newCodeSigningCert.Thumbprint)" -FilePath "$($certExport)\selfsigncert.pfx" -Password $CertPassword Happy scripting! Remember, signing your PowerShell scripts with a self-signed certificate adds an extra layer of security to your code. Stay vigilant, keep those scripts locked and loaded with your personalized signature, and code on with confidence! Thanks for your time, really appreciate it! Take care and goodbye!

  • MDT with SQL Database Access. Issues (ZTI Error opening SQL Connection)

    Microsoft’s Deployment Toolkit (MDT) supports integration with SQL Server providing far better control over deployment options, eg Client A gets Task Sequence 1, whereas Client B gets Task Sequence 2, both are assigned their respective static IP's. Previously I completed a comprehensive series on deploying MDT (here) including SQL Server Express integration and baulk import of client data into SQL. In this article, I’ll address common connection issues that may arise between MDT and SQL Server and how to fault find those issues. If you had followed the guides, the subsequent steps are likely unnecessary. Nevertheless, it is beneficial to offer guidance on diagnosing connection issues. The current MDT server is equipped with SQL, but in my haste, I had overlooked certain post-integration steps. As a result, there is a noticeable delay at the 'CSetting' stage during the initial WinPE for client deployment. Certain prerequisites must be met, including the establishment of a functional MDT server and the installation and configuration of SQL Express with the necessary connection settings listed in CustomSettings. PXE boot a client to the point where it's possible to select a Task Sequence. As WinPE offers limited diagnostic functionality and tools, it's back to the basics with Notepad and logs. Press F8 to access the command prompt CD to 'X:\MININT\SMSOSD\OSDLogs\' or execute the following command: Notepad X:\MININT\SMSOSD\OSDLogs\ZTIGather.log Near the bottom of the log search for SQL Connection errors: ZTI error opening SQL Connection: Unable to establish database connection using [CSETTINGS] properties If you are not aware SQL uses the SQL Browser service on port UDP 1434 for application communications. Two potential issues warrant investigation. First, verify that the SQL Browser service is configured to start automatically by accessing services.msc. The second issue involves checking UDP port 1434 in the Inbound firewall rules. However, if you prefer to confirm the port, proceed with the following steps. Utilize either wf.msc or gpedit.msc to set up Windows Firewall Public Profile logging for dropped packets only following the example below. Restart and PXE the client to the Task Sequence window. On the MDT Server launch Notepad with Administrative permissions and open: C:\Windows\System32\Logfiles\Firewall\PFirewall.log Search for the IP of the client. Note the dropped packets on 1434. While on the MDT server, launch either gpedt.msc or wf.msc. Add an inbound UDP rule to allow port 1434. Return to the client, restart and then review the ZTIGather.log as previously demonstrated. The error is pretty self-explanatory. The MDT Service account requires login and access rights to the MDT SQL Database. Switch to the MDT Server and open SQL Server Management Studio. Browse to Security then Logins. Right click on Logins and select 'New Login' If you followed the preceding installation guides, you likely created a service account to grant access to the MDT share and its credentials are listed in CustomSettings.ini and BootStrap.ini. Add this account as a Windows Login to SQL. Adjust the User Mapping by granting db_dataread access to the MDT database for the service account. Review the ZTIGather.log after restarting the client for a final time and confirm the successful access to SQL. The settings for clients included in the MDT Database will now take precedence over CustomSettings.

  • Intel NUC as a Home Lab Server

    Sweating the Assets It's time to bid farewell to the ageing NUC hardware, the current NUCs are from the 5th and 6th generations, dating back to 2016, and they've been in constant operation since their initial deployment. These systems are now struggling to keep up with the demands placed on them, especially NUC2, which regularly maxes out its CPU as it valiantly attempts to handle the workload of running SCCM and SCOM. There's a little nod to one of the best Syfy series ever, cruelly cut short, comment below if you know the name of the series. What's a NUC The Intel NUC (Next Unit of Computing) is an ideal choice for home labs due to its compact form factor, versatility, high performance and energy efficiency. Depending on the NUC variant this miniature PC can pack a powerful punch, ranging from a lowly i3 to an i9 processor and dedicated GPU in the form of the Intel Raptor Extreme, making it perfect for various lab setups and experimentation. Windows Server and Hyper-V I'm pretty agnostic as long as it's Microsoft, only kidding. Deploying Windows Servers as Hyper-V hosts in a home lab environment offers several advantages and a few disadvantages. The key advantages are: Multipurpose Functionality: Hyper-V hosts can serve as versatile servers, not limited to just virtualization. They can join the domain, be managed via System Center Configuration Manager (SCCM), and be monitored through System Center Operations Manager (SCOM). DFS Replication: Hyper-V hosts can host Distributed File System Replication (DFSR) File Servers for replicating user and group shares, enhancing data redundancy and availability. Deduplication: The virtual machines running on Hyper-V hosts can take advantage of deduplication, which helps save storage space by eliminating redundant data. However, there are some disadvantages to consider: Complexity: Managing enterprise-level services, such as SCCM and SCOM, can be complex and may require significant setup and maintenance effort, even in a home lab environment. Cost: Subscribing to Microsoft's Action Pack, so Servers don't time bomb after 90 days inflicts an annual cost of £450. Luckily for me, the company picks up the cost, this is not an option for everyone. Intel NUC 13 Hardware I acquired the new Intel NUC from due to its competitive pricing, which proved to be a bit more budget-friendly in comparison to other websites. The hardware components that were acquired include a 2TB Samsung 990, which might be a bit overkill for running Windows OS and possibly hosting a virtual Domain Controller. In contrast, the 4TB 870 is intended to accommodate the bulk of the virtual machines (VMs). LN1359491 - Intel Arena Canyon i7 Tall NUC = £569.99 LN1192071 - 2x32G Corsair Vengence = £119.99 LN130047 - 2TB Samsung 990 PRO M.2 SSD = £161.99 LN1136891 - Samsung 4TB 870 EVO 2.5 = £189.98 Here's a quick how to install all the components: Install the Vengence RAM and the Samsung 990 Pro after carefully removing the base. Remove the 4 rubber grommets from the base. Slot the 4TB 870 EVO 2.5 connecting it to the SATA interface. Using the supplied screws secure the 2.5 SSD. Windows Server 2022 Installation Media Creating Windows boot media involves preparing a USB drive that can be used to install a Windows operating system. The initial and critically important step is to download the latest firmware and drivers, which you can access by following the provided link below. It seems that the drivers included for the Intel NUC 13 Pro aren't compatible with Windows Server 2022. However, the Intel LAN Drivers tailored for the Intel 12th Gen NUC do work. Intel LAN-Win11- As an optional step, you can download the latest Windows Server 2022 Cumulative Update and copy it to the USB pen. This ensures that when network connectivity is established the most recent Windows patches are applied. USB Preparations You can download Windows Media in the form of an .iso file from Microsoft or the Partner site at a cost of £450 per year (includes many other benefits). Double click the iso to mount it on your computer. Copy the entire contents of the mounted image to an empty USB drive. Don't forget to include the necessary drivers and firmware files on the USB drive as well. Windows Server Installation Once you've connected the NUC's power supply, KVM, and the network, insert the USB pen with the bootable Windows installation files and drivers. Then, power on the NUC. Windows will boot and then follow the installation prompts. At the point of selecting the disk ensure it's the Samsun 990. I'm going to split the 2Tb and allocate 120Gb to the Windows OS partition. Set the Administrator password at the prompt and then log on. Install the drivers, firmware and any additional patches and reboot where necessary. Run 'diskmgmt.msc' to create any required partitions and assign drive letters. Run 'sysdm.cpl' and enable Remote Desktop access, allowing the NUC's KVM to be disconnected. Drivers for the Onboard NIC Now to resolve the connectivity issues and install the network drivers. At the run command type "Devmgmt.msc", select the network device and update drivers. Select 'Browse my computer for drivers' Select 'Let me pick from a list of available drivers on my computer' Select 'Have Disk...' and then browse to the Intel NIC drivers for the NUC Gen 12. Select the 'Killer E3100 2.5 Gigabit Ethernet Controller'. Select 'Yes' to the warning. Either set an IP address or allow DHCP to automatically assign an IP. Check for Windows Defender and any other missing updates. Hyper-V Setup Open PowerShell as Administrator (elevated) and execute the following command to install Hyper-V: Install-WindowsFeature -Name Hyper-V -IncludeManagementTools -Restart Once restarted configure the following Hyper-V settings: Create a new 'External' virtual switch, allowing management operations. Set the Virtual Hard Disks and Virtual Machines to point to the 4Tb 870 partition, mines on Z:\. Enable both Enhanced Session Mode check boxes. The NUC will be joined to the Domain with the LAPS, SCCM and SCOM agents installed automatically. The process of migrating VMs from the old NUCs is quite straightforward. Begin by removing any snapshots and shutting down the VMs. Then, proceed to perform a direct network copy of the VMs' directory structure to Z:\VM, followed by importing the VMs. Thanks For Your Time Thank you for taking the time to read this blog about the new Intel NUC for my home lab. We hope this information has been valuable. Stay tuned for more tech updates, and feel free to reach out if you have any questions or need further assistance.

  • RGB Office Transformation, from Drab to Fab

    Finding ways to make the home office more appealing and enjoyable is a constant. I've tinkered with RGB lighting and had some success over the years, but without a vision, it was incomplete, there's still room for improvement and let us be honest you can't have enough RBG. I've taken inspiration from CyberPunk as well as watching plenty of YouTube videos on office setups for Gamers. I'm also a big fan of Japanese Anime and Alter Carbon season 1. Let's not mention season 2, which dumbed down, mangled and then discarded the best bits of books 2 and 3, I'd like to take you on a tour of the transformation from an uninspiring (boring) office, as demonstrated by the picture below, into a visually appealing office with the simple use of RGB lights and some work focus tech upgrades. The Lighting: Govee Glide Hexa Light Panels * 20 Panels - £380 Govee Alexa LED Strip Lights 10m - £31 LED Aluminum Profile U Shape 6Pack 1M - £22 FEAHRZEUG Smart LED Ambient Light Bars - £35 KSIPZE 30m Led Strip Lights RGB - £21 The Govee Hexa panels support 12 connected panels via 1 power supply. Or linking all 20 panels with both power leads attached. For me, this would have resulted in leads trailing down the wall. So, I've opted for 2 separate 10 panel configurations. The overall connectivity had its limitations, given that each panel had just one input and one output. This constraint restricted the scope for creating more intricate patterns. The cheaper and less LED dense KSIPZE strips were discreetly installed under the desk or in less conspicuous areas. While the Govee's higher density LED's were placed inside the diffusers. The hobby that I get paid for is IT, the upside is that it requires lots of gadgets and tech for testing and development. The downside, without a doubt, is the cost involved. However, I see it as an investment. The more I invest in making things quicker, more efficient, and more effective, the quicker I can complete projects. This helps me justify the following monitor upgrades..... The 34" monitors were been switched out for an LG 40WP95CP and LG 27UL550P. The LG 40WP95CP 40" monitor has a pixel density of approximately 140 PPI, compared to the typical range between 55 to 110 PPI. While this lower pixel density might be suitable for gaming, it's less than ideal for office-based productivity tasks where a higher pixel density often leads to sharper and more detailed on-screen content. The 27” is orientated in portrait for the long read and scripting. The only issue is that the refresh rates on both monitors reduces to 30Hz as the main workhorse laptop’s GPU isn’t up to the job. The reduction of refresh rate isn’t a massive issue as I’m not a PC gamer and YouTube doesn’t seem to be too badly affected. But it does tell me that more hardware is required, something water cooled with internal RBG. Of course, no CyberPunk office is complete without a cityscape and a very cool car Etsy Mcarlen P1 - Standard Post 50cm * 70cm - £74 EleksMaker Elekstube IPS Nixie Tube Digital Clock Now, onto my favourite part, the Nixie Tube clock. While it's not a genuine Nixie Tube due to their high cost, this is an excellent alternative, featuring six distinct clock faces, including a simulated Nixie Tube display. - £243 - £150 + £12 expedited delivery Thank you for taking the time reading this blog regarding the RGB office upgrades Stay tuned for more updates, as I'm hoping to add further enhancements, any ideas would be gratefully received.

  • Deploy Domain Controllers with PowerShell and JSON (Part 1) - Domain Controllers

    How to deploy Domain Controllers with PowerShell and JSON? In my experience, while there are numerous Windows Server administration tasks suitable for automation, promoting Domain Controllers or deploying a new Forest is not typically among them. Automating Dcpromo can raise the risk of inadvertently exposing plain-text credentials in scripts, which is far from an ideal situation. Furthermore, such tasks are not frequently performed on a daily basis or repeated regularly in standard bau tasks. And now the Thousandath Time lets Lab a Domain Recently I've been engaged in a fair amount of lab work, involving dismantling and rebuilding domains. One such lab involved using Cloudformation, AWS and deploying a domain via Desired State, pre-packaged code provided by AWS. After going through the experience, I couldn't help but feel that I could deploy a Microsoft Domain setup far more effectively than relying on AWS and so we're here and I've a new PowerShell project to keep me amused... enjoy. The First of Many This is the first instalment of a two-part blog series. In this post, we'll delve into the automated deployment of a Domain using PowerShell in tandem with a JSON configuration file. This setup encompasses installing essential features such as DNS and AD and automatic logins via scheduled tasks. In the second blog, the focus will shift towards the deployment of Organizational Units (OUs) and Group Policy Objects (GPOs) with Restricted Groups, User Rights Assignments and implementing a comprehensive delegation model. The Requirements A standalone, not domain joined Windows 2022 with an active network is required, I'll be using a Hyper-V VM to host that VM. Testing has exclusively been carried out on Server 2022, the scripts should work with Server 2016 and 2019, it's important to note that I'm unable to provide any guarantees. Download all the files from GitHub (here) to the server, and save them to the Administrator Desktop, the 2 zip files will unpack automatically via the script. The Important Stuff Update DCPromo.json, the hostname of the server must match the "PDCName" value. "FirstDC": { "PDCName":"DC01", "PDCRole":"true", "IPAddress":"", "Subnet":"", Either update the passwords in the JSON file or update "PromptPw":"false" to "true". Once set to true the script will prompt for the password to be entered interactively. Regardless, the password is set in clear text into the Registry to allow autologin and later removed during the OU configuration. "DRSM":"Password1234", "DomAcct":"Administrator", "DomPwd":"Password1234", "PromptPw":"false" Any subsequent Domain Controllers can be added, remember that the hostname is the key and the value referenced during deployment. { "DCName":"DC02", "PDCRole":"false", "IPAddress":"", "Subnet":"", "DefaultGate way":"", "SiteName":"Default-First-Site-Name", "DRSM":"Password1234" }, Elevate PowerShell or ISE to execute DCPromo.ps1. Installation of Roles and DCPROMO As long as the above criteria are met, Windows Server will install AD-Domain-Services and DNS Windows Features, set the IP and DCPromo the server to become the first DC in the Forest and the PDC Emulator. Auto-Restart The newly promoted DC will auto-restart twice, this is required to correctly pass domain credentials to execute CreateOU.ps1 the final script.

  • Deploy Domain Controllers with PowerShell and JSON (Part 2) - OU Structure and Delegation

    Welcome Back Welcome back to the continuation of our series on deploying Domain Controllers using PowerShell and JSON. If you've been following along with Part 1, you should now have a newly configured Domain Controller with a delegated Organizational Unit (OU) structure in place. If you missed Part 1 of the series, you can access the necessary files by following the provided link or reference, (here). This blog will provide an in-depth explanation of the delegation model that has been delivered by PowerShell. It will also delve into the intricacies of the Organizational Unit (OU) structure, the arrangement of nested Groups and the various Roles assigned. Aim of the Game The objective is to establish an Organizational Unit (OU) structure that aligns with a clear and consistent delegation model. This approach incorporates well-defined naming standards to enhance comprehensibility and facilitate ease of navigation and management within the structure. AD Group Best Practice Group management will follow Microsoft's best practice of assigning Domain Local groups against the object, eg an OU or GPO. The Domain Local group is then added as a 'Member of' a Domain Global group. The user is added to Domain Global as a 'Member'. The naming convention I've persisted with over the years, again from Microsoft, is naming delegation groups 'Action Tasks', a task being an individual permission set. And 'Roles', a role being a collection of Tasks or individual permissions. AG is Action Task Global Group AL is Action Task Domain Local Group RG is a Role Global Group RL is a Role Domain Local Group Again, something that I've persisted with over the years is that Groups and OUs are named based on their Distinguished Name (DN). Let's break down an example of a group name: AG_RG_Member Servers_SCCM_Servers_ResGrpAdmin AG\AL\RG\RL - Action Task Global, AL for AT Domain Local, R for Role RG\OU\GPO - Restricted Group, OU or GPO - Type of object delegation Member Servers - The Top-Tier OU name SCCM - The Application or Service eg SCCM or Certificates Servers - It's for Computer objects ResGrpAdmin - ResGrpAdmin is a Restricted Group providing Admin privileges. ResGrpUser is a Restricted Group providing User privileges. CompMgmt, create\delete and modify Computer objects. UserMgmt, create\delete and modify User objects. GroupMgmt, create\delete and modify Group objects. GPOModify, edit GPO settings. SvcMgmt, create\delete and modify user objects. FullCtrl, full control over OU's and any child objects. JSON OU Configuration Traditionally there are only 3 tiers, the lower the tier the less trustworthy: Zero = Domain Controllers and CA's One = Member Servers Two = Clients and Users Given that this script can potentially generate numerous levels or hierarchies, it seemed more suitable to avoid the term "tier" and instead opted to label the top-level OU's as "Organizations" for a more meaningful representation. The JSON configuration provided creates an OU structure based on a default OU structure for many businesses, where Orgainisation1 is for Member Servers and Orgainisation2 is for Clients and Users. In addition, Organisation0 provides Admin Resources OU for the management of all delegation, role and admin account provision. Organisation0 - Admin Resources Organisation0, creates a top-level management OU named Admin Resources' This OU serves as the central hub for all delegation and management groups across subsequent Organizations. Each Organization benefits from having its own dedicated management OU within the Admin Resources OU. Organisation specific delegation groups, roles, and admin accounts are created. This approach allows for potential future delegation. Admin Accounts Member Servers Admin Tasks Member Servers Admin Roles Member Servers "OU": { "Organisation0": { "Name":"Admin Resources", "Path":"Root", "Type":"Admin", "Protect":"false", "AdministrativeOU":"Administrative Resources", "AdministrativeResources": [ "AD Roles,Group", "AD Tasks,Group", "Admin Accounts,User" ] }, Organisation1 - Member Servers Organisation1 represents the typical Member Server OU and it's of the Type Server. The type Server designates a behavioural difference for assigning policy. AppResources designates application service OU's that will be created eg Exchange. Service Resources is used for creating OU's based on a set of standard administrative functions for example Servers and the delegation and object type of Computers. "Organisation1": { "Name":"Member Servers", "Path":"Root", "Type":"Server", "Protect":"false", "AdministrativeOU":"Service Infrastructure", "AdministrativeResources": [ "AD Roles,Group", "AD Tasks,Group", "Admin Accounts,User" ], "AppResources":"Certificates,MOSS,SCCM,SCOM,File Server,Exchange", "ServiceResources": [ "Servers,Computer", "Application Groups,Group", "Service Accounts,SvcAccts", "URA,Group" ] }, Organisation2 - Client Services Organisation2 represents the typical User Services OU and it's of the Type 'Clients'. "Organisation2": { "Name":"User Services", "Path":"Root", "Type":"Clients", "Protect":"false", "AdministrativeOU":"Service Infrastructure", "AdministrativeResources": [ "AD Roles,Group", "AD Tasks,Group", "Admin Accounts,User" ], "AppResources":"Clients", "ServiceResources": [ "Workstations,Computer", "Groups,Group", "Accounts,User", "URA,Group" ] } } Hundreds and thousands It's possible to add further top-level OU's by duplicating an Organisation, then updating the Organisation(*) and Name values as they need to be unique. It's possible to add hundreds or even thousands of Organisations, with this possibility in mind, the management and delegation structure reflects this within the design. Levels of OU Delegation As we delve deeper into the structure of each organization, we encounter a hierarchy consisting of three levels of delegation, using Member Servers as an example: Organisation = Member Servers (Level 1) Application Service = Certificates (Level 2) Resources = Computer, Groups, Users and Service Accounts (Level 3) OU delegation controls the level of access to manage objects eg create a Computer or Group object. Level 1 Level 1 is the organisation level in this case it's the Member Server OU. It's delegated with AL_OU_Member Servers_FullCtrl. The group provides full control over the OU, sub-OU's and all objects within. The arrow serves as an indicator, denoting the point at which the group's application takes effect within the structure. Level 2 Level 2 is the Service Application level, in this case, Certificate services. AL_OU_Member Servers_Certificates_FullCtrl is applied a level below Member Servers and provides full control over itself and any subsequent objects. Level 3 At Level 3, the delegation involves the management of Service Applications resources, which includes items such as Server objects and service accounts. The 4 default OU's allow the delegation and management of their respective resource types, for example, the Application Groups OU permits the creation and deletion of Group objects via AL_OU_Member Servers_Certifcates_Applications Groups_GroupMgmt. Application Groups - Application specific Groups Servers - Server or Computer objects Service Accounts - Service Accounts for running the application services URA - User Rights Assignments for services that require LogonAsAService etc Restricted Groups and User Rights Assignment (URA) Levels In this delegated model, Restricted Groups facilitate access by allowing administrative access whilst User Rights Assignments (URA) allow admins or users to log on over Remote Desktop Protocol (RDP). There are two primary levels of organization. The first level encompasses the entire organization, including all subsequent Organizational Units (OUs). The second level consists of a dedicated Servers OU for each specific Service Application. Level 1 of Restricted Groups The GPO GPO_Member Server_RestrictedGroups is linked to the Member Servers OU and has the following groups assigned: URA: Allow log on through Terminal Services: AL_RG_Member Servers_ResGrpAdmin AL_RG_Member Servers_ResGrpUser Restricted Group: Administrators: AL_RG_Member Servers_ResGrpAdmin Remote Desktop Users: AL_RG_Member Servers_ResGrpUser This is how it looks when applied in GPO. Within this delegation model, the ability to manage Group Policy Object (GPO) settings is also delegated to ensure comprehensive control and management of the environment. via AL_GPO_Member Servers_GPOModify Group. Level 2 of Restricted Groups The GPO GPO_Member Server_Certificates_Servers_RestrictedGroups is linked to the sub-OU Servers under Certificates and has the following groups assigned, that of the Organisation and of the Service Application: URA: Allow log on through Terminal Services: AL_RG_Member Servers_ResGrpAdmin AL_RG_Member Servers_ResGrpUser AL_RG_Member Servers_Certifcates_ResGrpAdmin AL_RG_Member Servers_Certificates_ResGrpUser Restricted Group: Administrators: AL_RG_Member Servers_ResGrpAdmin AL_RG_Member Servers_Certifcates_ResGrpAdmin Remote Desktop Users: AL_RG_Member Servers_ResGrpUser AL_RG_Member Servers_Certificates_ResGrpUser This is how it looks when applied in GPO. As above Group Policy Object (GPO) settings are also delegated via AL_GPO_Member Servers_Certificates_Servers_GPOModify Bringing it all together with Roles In this demonstration, an account named 'CertAdmin01' has been specifically created to oversee the management of resources within the Certificates OU. The account is added to the role group RG_OU_Member Servers Certificates_AdminRole. Opening the RG_ group and then selecting the 'Members Of' tab displays the nested RL_ group. Drilling down into the RL_ group displays the individual delegated task groups. Delegated Admin To test the certificate Admin (CertAdmin01) deploy an additional server, adding to the domain and ensuring the computer object is in the Certificate Servers OU. Login as CertAdmin01 to the new member server and install the GPO Management and AD Tools. Browse to Member Server and then Certificates OU and complete the following tests: Right-click on Applications Group > New > Group Right-click on Servers > New > Computer Right-click on Service Accounts > New > User Right-click on URA > New > Group. Open Group Policy Management and Edit GPO_Member Servers_Certificates_Servers_RestrictedGroup. Open Compmgmt.msc and confirm that the Administrators group contains the 2 _ResGrpAdmin groups and the local Administrator. AL_RG_Member Servers_Certificates_Servers_ResGrpAdmin AL_RG_Member Servers_ResGrpAdmin Confirm that CertAdmin01 is unable to create or manage any object outside the delegated OU's. Nearly there.....SCM Policies and ADMX Files As part of the delivery and configuration of the OU structure, Microsoft's Security Compliance Manager (SCM) GPOs and a collection of Administrative (ADMX) templates are included. SCM GPOs: Microsoft's SCM offers a set of pre-configured GPOs that are designed to enhance the security and compliance of Windows systems. These GPOs contain security settings, audit policies, and other configurations that align with industry best practices and Microsoft's security recommendations. ADMX Templates: ADMX files, also known as Administrative Template files, extend functionality within Group Policy Management enabling settings for Microsoft and 3rd party applications. Within a Domain, ADMX files are copied to the PolicyDefinition directory within Sysvol. Zipped... Both SCM and ADMX files are zipped and will automatically be uncompressed during the OU deployment. However, if you would like to add your own policies and ADMX files you can. SCM Policy Placement The SCM policies are delivered in their default configuration, without any modifications or merging. The policies are placed directly into the designated target directory, imported and linked to their respective OU. For example, the Member Server directory content will be linked to any OU that is of type 'Server'. The SCM imported policies are prefixed with 'MSFT,' indicating that they are Microsoft-provided policies. There are a substantial number of these policies linked from the root of the domain down to client and server-specific policies. As far as delegation the SCM policies remain under the jurisdiction of the Domain Admin with control to effect change delegated to the _'RestrictedGroup' policies. Thank you for taking the time to read this blog. I hope you found the information valuable and that it has been helpful. Your support is greatly appreciated!

  • Identify and Fix Unquoted Paths Vulnerability Automatically

    The unquoted paths vulnerability is a security flaw that occurs when a software application or service running on a system references executable files or scripts without enclosing the file path in quotation marks. This can lead to a potentially exploitable security gap because the operating system interprets the unquoted path incorrectly. ​ When a program with an unquoted path runs, the OS may attempt to execute the name of the directory with the space. C:\Program.exe C:\Program Files (x86)\Application.exe C:\Program Files (x86)\Application One\ An attacker can place a malicious executable in a directory with a similar name to the one referenced in the unquoted path. When the vulnerable program runs, it might mistakenly execute the malicious code, enabling unauthorized access, privilege escalation, or other security breaches. ​ To mitigate this vulnerability, developers should always use quotation marks around file paths in their code to ensure that the correct executable is executed, and users should keep their systems updated to patch any discovered unquoted paths. vulnerabilities. For demo purposes, the system has been intentionally afflicted with unquoted path vulnerabilities. This output is from a dedicated Unquoted script found @ This output is from a far more extensive suite of scripts that search many vulnerabilities and configuration errors and present the results in an HTML format that can be imported into Excel and can be found @ While the capacity to spot vulnerabilities is valuable, my approach focuses on automatically addressing these issues during deployments whilst also reviewing the output. Resolving security vulnerabilities is then built into MDT and SCCM (MECM) Task Sequences. Equally, the reporting and resolution of this issue can be accomplished manually by executing the scripts with Admin privileges from PowerShell. No manual intervention is required, any application that falls through the gaps eg a member of staff deploying an app without following the process, that's if the process exists. Back to Github to download the 2nd script that 'fixes' Unquoted paths. Output is provided to any actions taken both to PowerShell and a log file. The script adds the double-quotation marks both preceding and following the imagepath, ensuring that the path is properly enclosed within quotation marks.

  • Audit Applocker Rules and Export to Excel

    Introduction Reporting on AppLocker rules is crucial to maintaining security. It provides insight into allowed and blocked applications, aiding in policy refinement. The main challenge lies in the absence of a management graphical user interface (GUI) for rule administration and processing. Indeed, GPResult offers a visual display of individual policies, but it falls short in presenting a comprehensive overview of the combined and applied policies. A Quick Recap of Applocker A quick recap. AppLocker is a security feature available in Windows that provides user context application control. It uses policies based on file attributes like publisher, hash, and path to allow or deny software execution. By preventing unauthorized or potentially harmful programs from running, AppLocker helps safeguard systems against malware and unauthorized software installations, enhancing overall security. As Applocker only protects the user context it provides little safeguard against RCE. Applocker is also subject to numerous Living off the Land bypasses and should only ever be considered part of a layered approach to Windows security. Windows Defender Application Control is a far more robust kernel level application control mechanism. The Script The script for exporting Applocker rules can be found @ Why Export to HTML!!! If you hadn't realised the script initially creates an HTML report, but the original intention was to export Applocker Rules to .csv, then into Excel. Exporting to CSV proved limiting due to the lack of support for individual worksheets or pages. The report must also work on Clients, Servers and not be reliant on Excel or imported Excel PowerShell modules. Finally, I've an extensive configuration, security and vulnerability assessment report written in PowerShell, likewise creating an HTML report that also can be imported into Excel. The vulnerability assessment script can be found @ The Report Download the script and execute it using PowerShell_ISE or native PowerShell. While I haven't conducted extensive testing with PowerShell, it should function in both environments. The report outputs to $env:USERPROFILE, the root of the user's profile path, named the date, hostname-report.htm "C:\Users\Fred\23-08-28-LP674504-Report.htm". The report will contain the effective policy applied to the endpoint. While appealing, the current format may not be the most practical to work with. However, you can import it as a web source into Excel, where each heading corresponds to an Excel worksheet. Here are a couple of examples followed by a quick how-to for importing into Excel. Excel Import Once the script concludes, the AppLocker Audit report will automatically open in the default web browser. Copy the URL path to the clipboard for use in the importing process. Open Excel and go to the Data tab, then select 'From Web'. Paste the file path into the URL box. In the navigation Window, select the Applocker Rule sets and then 'Load' and 'Load To...' on the drop down. Select 'Table' on the Import Data window. Importing the HTML file into Excel requires a brief moment, although it won't provide sufficient time to justify indulging in a coffee break. Upon completing the import process, an Excel spreadsheet is prepared and readily available for review. Hope this proves useful, feedback is always welcome and thanks for your time.

  • Change MDT Mapped Z: Drive

    When deploying a Windows operating system or installing MDT applications, a mapped network drive is usually mounted temporarily as Z:\. The letter "Z" is chosen because it is typically not used for local drives in most deployments, it's less likely to conflict with existing drive letters on the target computer. What occurs when an application necessitates the use of the Z:\ drive during the process of deploying an image through MDT? It's often better to overlook your initial reaction.....Z: Being engaged during the operating system installation. Applications can persist with preconfigured mapped network drives. The illustration provided represents a common example of a regular operating system deployment, and it's evident that the drive letter Z: is assigned to the MDT Deployment share. There appear to be two approaches to altering the fixed Z:\ drive mapping to a different designated letter, although there might be additional methods available as well. During my search for a solution, Google yielded no results, which could potentially be attributed to me asking the wrong questions. Late to the party and whilst writing this blog, ChatGPT provided a suggestion to address this issue, update the 'CustomSettings.ini' file by incorporating 'DriveLetter=Y'. Had it succeeded on the initial attempt, it would have presented a more graceful resolution, unfortunately, that wasn't the case, I haven't delved into the reasons behind the failure. Let's proceed with a working solution by modifying the hardcoded drive letter in ZTIUtility.vbs. I'm using PowerShell_ISE as it conveniently displays the line number. Browse to C:\MDTDeploymentShare\Scripts\ZTIUtility.vbs Search for "z" and on line 3003 or thereabouts, depending on the version of MDT installed, update the hardcoded drive 'Z' to something else, not C: or X: as these are also used by the OS and MDT. In this case, I've designated the letter 'T' as the new MDT mapped network drive. Regenerate the Boot images by Updating the Deployment Share. Choose 'Completely regenerate the boot images', then grab a coffee. Launch WDS and Replace the Image. Browse to the MDT Share and select the LiteTouchPE_x64.wim. Deploy a new Windows OS from MDT Pxe and the MDTDeploymentShare is now mapped as "T:\". If you found the content valuable, I encourage you to explore the MDT deployment guides and instructional resources available under the main website sections. Finally, I'm headed off to have strong words with the individual responsible for implementing an application that requires hardcoded drives for configuration components.

  • PowerShell's Custom Runtime for AWS Lambda's - Installation

    Introduction PowerShell custom runtime for AWS Lambda is an addition to the AWS Lambda services, offering developers and Microsoft engineers the ability to leverage PowerShell within the serverless environment. Unlike the standard runtimes supported by AWS Lambda, which include languages like Python, Node.js, and Java, the PowerShell custom runtime, developers can now build and deploy Lambda functions using their existing PowerShell skills. It allows for the integration of PowerShell's vast library of cmdlets and modules, enabling developers to leverage a wide range of pre-built functions and automation tasks. PowerShell's object-oriented scripting approach also provides a means for manipulating and managing AWS resources, making interacting with other AWS services like Amazon S3, Amazon DynamoDB, and AWS CloudFormation easier. Additionally, it's now possible to edit the PowerShell script directly within the published Lambda, which was not previously possible. The Truth of the Matter The issue, it's PowerShell, any real DevOps will be using anything but PowerShell as it's a scripting language, so there's limited support for PowerShell on AWS. However, if you're a Microsoft engineer who needs to manage the Windows Infrastructure on AWS then PowerShell will be your go to scripting language for Lambda functions. The PowerShell custom runtime setup provides 3 options for deployment, Linux or WSL, native PowerShell and Docker. The native PowerShell deployment doesn't work, at least I couldn't get it working and others have faced similar issues, with no resolution provided. The good news is that Windows Subsystem for Linux (WSL) deployment does successfully deploy and execute and this is what I'll be using. Requirements WSL 2 requires the Hyper-V Hypervisor, this rules out any AWS EC2 instance, Hyper-V isn't supported. A Windows 2022 or Windows 11 with the latest patches installed is required. I've Windows 11 installed on a Zenbook Space Edition laptop with the Hyper-V feature installed and virtualization enabled in the system's BIOS or UEFI. WSL 2 isn't directly installed on the laptop, it can be, I prefer keeping my clients free of clutter and instead opted for a Windows Server 2022 Hyper-V vm. Any issues the vm will be rolled back or redeployed. Now deploy a Gen2 Windows Server 2022 Hyper-V image named, ensure the latest Windows updates are applied. AWS Configuration An account named 'svc_lambda' has been created with Administrative access in IAM. The excessive rights are for ease of deployment, the permissions will be adjusted to those needed later. The account's Access and Secret have been exported for use during the creation of the PowerShell Runtime Lambda. Installation of Windows Subsystem for Linux version 2 WSL version 2 was not supported by Server 2022 or Windows 11 at release. Install the latest Windows patches to enable WSL2 support. I may have mentioned this a few times now. Power off the VM and from the host open an elevated Powershell session. Then type the following command to enable nested hypervisor. AWS-Mgmt01 is vm's name in the Hyper-V console and not its hostname. Set-VMProcessor -VMName AWS-Mgmt01 -ExposeVirtualizationExtensions $true Power on, AWS-Mgmt01, login and elevate a PowerShell session and execute the following command. This will install all components and features required. If the command fails to be recognised, then Windows updates aren't applied or the experience I had, they failed to install correctly. wsl --install Restart AWS-Mgmt01, log in and WSL should auto launch, if not run wsl --install from PowerShell. Type in a username and password at the prompt. Installation confirmation will show that the latest version of Ubuntu and WSL 2 are configured. In the Linux shell execute the following commands to update and install all required dependencies. sudo apt update -y && sudo apt upgrade -y sudo apt install glibc-source groff less unzip make -y AWS Serverless Application Model Installation AWS SAM (Serverless Application Model) is a framework provided by AWS that simplifies the development, deployment, and management of serverless applications. It extends the capabilities of AWS CloudFormation, allowing developers to define serverless application resources using a simplified YAML syntax and is next to install. Type pwd and it will return '/home/user'. Type: mkdir Downloads to create a working directory and cd into the directory. Download the SAM client for Linux, unzip and Install. wget unzip -d sam-installation sudo ./sam-installation/install Confirm version and successful installation. /usr/local/bin/sam --version Download the AWS Client for Linux, unzip and Install wget "" unzip sudo ./aws/install Confirm version and successful installation. /usr/local/bin/aws --version Download the AWS Lambda PowerShell Runtime. git clone mv aws-lambda-powershell-runtime/ aws-sam cd aws-sam/examples/demo-runtime-layer-function Export the access and secret keys for the Lambda service account via AIM. Configure access for the Lambda-Svc user. aws configure AWS Access Key ID [None]: AKIA5IZEOZXQ4XXXXX AWS Secret Access Key [None]: 2O8hYlEtAzyw/KFLc4fGRXXXXXXXXXX Default region name [None]: us-east-2 Default output format [None]: Build the custom runtime . sam build --parallel Deploy Custom Runtime to AWS. sam deploy -g Stack Name [sam-app]: PowerShellLambdaRuntime AWS Region [us-east-2]: us-east-2 Confirm changes before deploy [y/N]: n Allow SAM CLI IAM role creation [Y/n]: y Disable rollback [y/N]: n Save arguments to configuration file [Y/n]: n The deployment will take a few minutes as it creates CloudFormation, an S3 bucket and finally the Lambda. Testing the Runtime Lambda Function From the AWS console, open Lambda and browse to Functions to confirm the successful deployment of the PowerShell Runtime Demo. It's at this point when native PowerShell is used, the whole runtime falls apart and fails to execute. Click on Test after reviewing the PowerShell code. This is a first not only can it be viewed, it's editable. Add an Event Name and Save. Click on Test and review the details. The Runtime is installed, but not much else..... This is just the beginning and a bit of a problem if you thought that it was a simple matter of creating new Lambda's and applying PwsRuntimeLayer. I'm the bearer of bad news, let me explain. Two layers were created for the demo, the DemoAWSToolsLayer and PwshRuntimeLayer. For PowerShell, the correct modules need importing and these are supplied in the Lambda layers. In this case, it's the DemoAWSToolsLayer that loads the required module for the Lambda demo. And in the Demo's case, it's only the AWS.Tools.Common module needed by the function to the Get-AWSRegion. Consequently, additional layers containing the necessary modules for the function are required. For instance, to create a Lambda function to stop an EC2 instance, both the AWS.Tools.Common and AWS.Tools.EC2 modules are needed. We will delve into this in the next blog (here). Links

  • PowerShell's Custom Runtime for AWS Lambda's - Importing Modules

    Welcome to the second part of the installation and configuration process for the AWS Custom Runtime for PowerShell Recap In the first part, we covered the installation process of AWS's Custom Runtime for PowerShell, which involved deploying Windows Subsystem for Linux (WSL) and initializing the Runtime and deploying the Demo Lambda Function. Here's the link. with instructions on how to instal WSL and deploy the Custom Runtime. What's in Part 2 The first part left on a bit of a cliffhanger, functionally, the Custom Runtime for PowerShell worked, but without additional modules, there's very little that could be accomplished. The subsequent steps entail the creation of Lambda layers that incorporate additional modules, which will be utilized in Lambda Functions to finalize the end-to-end deployment process. Copy and Paste Upon completing this process, the objective is to successfully deploy a Lambda Function equipped with a layer containing both the AWS.Tools.Common and AWS.Tools.EC2 PowerShell modules. This will enable the ability to start and stop an EC2 instance within the AWS environment. Continuing where we previously left off, we are going to utilise the work that has already been completed by AWS, by amending an existing example. Before we start, only 5 layers can be added to a Lambda Function, but a layer can contain multiple modules. Change the directory into the AWSToolsforPowerShell directory. cd /Downloads/aws-sam/powershell-modules/AWSToolsforPowerShell Copy the existing S3EventBridge directory. cp AWS.Tools.S3EventBridge AWS.Tools.EC2 -r cd AWS.Tools.EC2 Amendments The 3 files that will require amending to successfully publish additional modules as layers are: build-AWSToolsLayer.ps1 template.yml /buildlayer/make The process is straightforward, find and replace all references to the current module functionality with the new module functionality. Although updating build-AWSToolsLayer.ps1 is not strictly essential since we'll be relying on the Make command, taking a few seconds to do so ensures consistency among all the files involved. nano build-AWSToolsLayer.ps1 Ctrl + o to save (output the file) Ctrl _ x to exit nano Add additional lines for modules that are to be extracted from Note: It is crucial to ensure the correct ordering of modules, with AWS.Tools.Common listed before the module for EC2. The EC2 module relies on the functionality provided by AWS.Tools.Common. In the original S3EventBridge version of template.yml AWSTools.EC2 read S3EventBridge. Ensure !Ref values are updated from AWSToolsS3EventBridgeLayer to AWSToolsEC2Layer, this value is passed between files and needs to be consistent. Save and exit template.yml. cd buildlayer nano Make The first line references !Ref and it must be consistent with the value set in template.yml. Modify the unzip commands to accommodate any supplementary modules. Save and exit Make. Build and Deploy After each amendment to the configuration files, the content must be redeployed in order to reflect the changes made: sam build To publish to AWS run the following: sam deploy -g Layers and a Lambda Login to AWS Lambda and confirm the new layer has been created. Let us bring the entire Custom Runtime endeavour to fruition, by creating a new Lambda Function designed to initiate the start of an EC2 Instance, by clicking Create Function. Name the function and select the Amazon Linux 2 Runtime. Ensure the Architecture is set to x86_64. 'Create a new role with basic Lambda permissions' is also selected. Create Function Within the Function Overview click on Layers, then Add Layers. Select Custom Layers and then add in order: PwshRuntimeLayer AWSToolsEC2Layer PwshRuntimeLayer is listed first, followed by any modules. Click Configuration and Edit Update memory to 512Mb and timeout to 1 minute. Before saving the configuration updates, open the IAM link in another browser tab to grant the function the additional permissions required for execution. Within IAM, add AmazonEC2FullAccess and AWSLambdaExecute to the Role. Navigate back to Lambda and then select Code. Update the Runtime Settings Handler information to reflect the name of the PowerShell script followed by "::handler". In this example, the handler will be "Start-Ec2.ps1::handler" Navigate back to Code and delete all the default files. Right-click on the folder and New File, rename to "Start-Ec2.ps1". Copy and paste the provided script, and make sure to modify the Reservation ID with the ID of your own EC2 instance. Deploy the changes. Click Test Complete the Configure Test Event by providing an Event Name. Navigate to the Test tag and click Test to execute the Lambda Function. I'm hoping this guide provides a starting point for further modules and functionality, especially those that come from a native Microsoft background. I wish to thank everyone for their time and any feedback would be gratefully received.

bottom of page