I was messing around with my test/dev virtual machine over on Azure, after having blown away the old one so that I could create one with Server 2022, and got tired of creating the pools and sites manually. The code below is the result of a few hours of research and tinkering around, but works well for what I am doing.
This first part is used when creating the main part of the domain on the server.
$Domain="domain.tld"
New-Item -ItemType Directory -Path "W:\inetpub\vhosts\$Domain\" -Name httpdocs
New-Item -ItemType Directory -Path "W:\inetpub\vhosts\$Domain\" -Name logs
New-Item IIS:\AppPools\$Domain
New-Item IIS:\Sites\$Domain -bindings @{protocol="http";bindingInformation="*:80:$Domain"} -physicalPath W:\inetpub\vhosts\$Domain
Set-ItemProperty "IIS:\Sites\$Domain" -name logFile -value @{directory="W:\inetpub\vhosts\$Domain\logs"}
Set-ItemProperty IIS:\Sites\$Domain -name applicationPool -value $Domain
Code language: PowerShell (powershell)
The code below is used for adding a subdomain, and would need to have the wildcard SSL issued for the related main domain already, which I am currently getting from Let’s Encrypt via the Certify the Web application in Windows.
$Domain="sub.domain.tld"
$Parent=$Domain.Substring($Domain.IndexOf(".") + 1)
$Child=$Domain.Split('.')[0]
$Cert = (Get-ChildItem Cert:\LocalMachine\My | Where{$_.Subject -eq "CN=*.$Parent"}).ThumbPrint
New-Item W:\inetpub\vhosts\$Parent\$Child -type Directory
New-Item IIS:\AppPools\$Domain
New-Item iis:\Sites\$Domain -bindings @{protocol="http";bindingInformation="*:80:$Domain"} -physicalPath W:\inetpub\vhosts\$Parent
Set-ItemProperty "IIS:\Sites\$Domain" -name logFile -value @{directory="W:\inetpub\vhosts\$Parent\logs"}
New-IISSiteBinding -Name "$Domain" -BindingInformation "*:443:$Domain" -CertificateThumbPrint $Cert -CertStoreLocation "Cert:\LocalMachine\My" -Protocol https
Set-ItemProperty IIS:\Sites\$Domain -name applicationPool -value $Domain
Code language: PowerShell (powershell)
Finally, two simple lines that can be used to remove the pool and site for any domain/subdomain.
Remove-WebSite -Name "$Domain"
Remove-WebAppPool -Name "$Domain"
Code language: PowerShell (powershell)