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
}
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 –
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
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:
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.
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.
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
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.
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).
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
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.
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.
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.
6. Finally, verify it’s working by losing connectivity!
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.
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:
We can also have a look at applied Computer policies using the /v parameter when running 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 /dsgetdc:<domain> queries DNS and returns a list of domain controllers (with IPs).
nltest /dsgetsite returns the site name of the domain controller.
nltest /sc_query:<domain> reports the state of the secure channel for when it was last used.
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 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;
The private IPv4 network has been configured, now we should verify we have line-of-sight.
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.
Enter the Domain Name.
Reboot once done.
When the box is up, you’ll have the option to login with the
Local Administrator account, or with another user.
If selecting Other user, you’ll have an entry for the domain
you’re signing into.
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.
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:
2. Enter the new OU name – I’m going to pretend I’m in the IT Department:
3. Within the IT OU, right-click and select New-User:
4. Enter new user details:
5. Enter password stuff:
6. Finish:
7. Right-click the new user and select Add to a group:
8. Enter king group, Domain Admins:
Joining a Windows Server to a Domain
1. First, I have to get onto the same private IP range as the DC:
2. Within Server Manager, click the Computer name link:
3. Click Change:
4. Amend the hostname and enter the Domain name:
5. Enter credentials for an account that can join the domain (the account created above within this post would also work):
6. When the server next boots up a domain user account can log in:
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.
1. Right-click the Hyper-V host and select Virtual Switch Manager.
2. Select Private and Create Virtual Switch.
3. Enter a name for the network and click okay.
4. Right-click the VM in Hyper-V and click Settings.
5. Add a new Network Adapter.
6. Select Private vSwitch as named above and click OK.
Configure Windows TCP/IP Settings
1. When the above has been set-up, Windows Server will show network settings as Identifying…
2. Right-click the network icon and click Open Network and Sharing Center.
3. Click the highlighted active Ethernet connection.
4. Open Properties.
5. Open Internet Protocol Version 4 (TCP/IPv4) Properties.
6. Enter IP and subnet addresses.
Rename the Windows Server Host
1. Open Server Manager and click the highlighted Computer Name.
2. Click Change…
3. Enter new Computer Name and click OK.
The host will require a reboot once done.
Installing Active Directory
1. Within Server Manager, click Manage > Add Roles and Features.
2. Before you begin, read the before you begin.
3. Select Role or Feature-based installation.
4. Select the destination server.
5. Tick the Active Directory Domain Services checkbox.
6. The following will appear – click to add the additional tools.
7. No features are being added at this time – click to continue.
8. ADDS page is worth a read – nothing to change here.
9. Review and click to install.
10. Leave it a few minutes and we’re then able to promote this server as a new Domain Controller.
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.
2. This is a new test environment, so I need to Add a new forest.
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.
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…
2. Enter the name of the new VM and the location on disk.
3. Select Generation of VM.
4. Enter the memory allocation amount.
5. Select a network connection (I’ll set this up later).
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).
7. Select an Operating System ISO file.
8. Review configuration and hit finish.
9. Power up the new VM!
Installing Windows Server 2016
1. Connect to the new VM (ensuring step 7 above was followed).
2. Hit any key.
3. After 30 seconds or so of loading, select your location.
4. Click to start the Windows Server installation.
5. GUI this time around, and Datacenter Edition for the test environment.
6. Accept the usual.
7. Check advanced options.
8. Install on the 50GB vHD.
9. Hit next, and away it goes…
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.