Shell execute in lua - powershell

powershell script
Set-ExecutionPolicy Unrestricted
## NEEDED FOR IIS CMDLETS
Import-Module WebAdministration
## CREATE FTP SITE AND SET C:\inetpub\ftproot AS HOME DIRECTORY
New-WebFtpSite -Name "test" -Port "21" -Force
cmd /c \Windows\System32\inetsrv\appcmd set SITE "test" "-virtualDirectoryDefaults.physicalPath:C:\inetpub\ftproot"
## SET PERMISSIONS
## Allow SSL connections
Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.ssl.controlChannelPolicy -Value 0
Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.ssl.dataChannelPolicy -Value 0
## Enable Basic Authentication
Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $true
## Set USer Isolation
Set-ItemProperty "IIS:\Sites\test" -Name ftpserver.userisolation.mode -Value 3
#Set-ItemProperty "IIS:\Sites\test" -Name ftpServer.security.userIsolation. -Value $true
## Give Authorization to Administrators and grant "read"/"write" privileges
Add-WebConfiguration "/system.ftpServer/security/authorization" -value #{accessType="Allow";roles="";permissions="Read,Write";users="*"} -PSPath IIS:\ -location "test"
## Give Authorization to All Users
#appcmd set config %ftpsite% /section:system.ftpserver/security/authorization /+[accessType='Allow',permissions='Read,Write',roles='',users='*'] /commit:apphost
## Restart the FTP site for all changes to take effect
Restart-WebItem "IIS:\Sites\test"
that I want to run it with lua
I make that script
function Create_iis()
tl1="Set-ExecutionPolicy Unrestricted"
tl2="Import-Module WebAdministration"
tl3="New-WebFtpSite -Name \"test\" -Port \"21\" -Force"
tl4="cmd \/c \\Windows\\System32\\inetsrv\\appcmd set SITE \"test\" \"-virtualDirectoryDefaults.physicalPath:C:\\inetpub\\ftproot\""
tl5="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.controlChannelPolicy -Value 0"
tl6="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.dataChannelPolicy -Value 0"
tl7="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $true"
tl8="Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpserver.userisolation.mode -Value 3"
tl9="Add-WebConfiguration \"\/system.ftpServer\/security\/authorization\" -value \#\{accessType=\"Allow\";roles=\"\";permissions=\"Read\,Write\";users=\"*\"} -PSPath IIS:\ -location \"test\""
tl10="Restart-WebItem \"IIS:\\Sites\\test\""
file = io.open("c:\\testiis.ps1","w");
file:write(tl1.."\n"..tl2.."\n"..tl3.."\n"..tl4.."\n"..tl5.."\n"..tl6.."\n"..tl7.."\n"..tl8.."\n"..tl9.."\n"..tl10.."\n"..);
file:close("c:\\testiis.ps1");
result = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe", "open", "c:\\testiis.ps1", "", SW_HIDE,true);
if result ~=0 then
Dialog.Message("Error", "Error ", MB_OK, MB_ICONSTOP, MB_DEFBUTTON1);
end
end
and work well
but I need to check for every line in this script if return error then exit
and give me the line that make the error
so I make stupid script that
function Create_iis()
result1 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ExecutionPolicy Unrestricted")
result2 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Import-Module WebAdministration")
result3 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","New-WebFtpSite -Name \"test\" -Port \"21\" -Force" )
result4 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","cmd \/c \\Windows\\System32\\inetsrv\\appcmd set SITE \"test\" \"-virtualDirectoryDefaults.physicalPath:C:\\inetpub\\ftproot\"")
result5 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.controlChannelPolicy -Value 0")
result6 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.ssl.dataChannelPolicy -Value 0")
result7 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpServer.security.authentication.basicAuthentication.enabled -Value $true")
result8 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Set-ItemProperty \"IIS:\\Sites\\test\" -Name ftpserver.userisolation.mode -Value 3")
result9 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Add-WebConfiguration \"\/system.ftpServer\/security\/authorization\" -value \#\{accessType=\"Allow\";roles=\"\";permissions=\"Read\,Write\";users=\"*\"} -PSPath IIS:\ -location \"test\"" )
result10 = Shell.Execute("C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe","open","Restart-WebItem \"IIS:\\Sites\\test\"")
end
and check for every result
but there are some commands that depend on each so it make error
it is impossible to make that ?
sorry for poor English
Thanks in advance

You can use io.popen to call a command in Lua:
local file = assert(io.popen('/bin/ls -la', 'r'))
local output = file:read('*all')
file:close()
print(output) -- > Prints the output of the command.
source: https://stackoverflow.com/a/5243210/1069083

Related

Set App Pool recycle time with PowerShell trouble

I want to set two specific times to recycle my App Pools in IIS.
In the GUI, if you want to set multiple specific times you enter it like so 00:15, 04:30.
Below is my PowerShell. It only sets the first time - 00:15. Unfortunately, no error is happening, and so there is no error to post.
Why is this only setting the first time? I am using New-ItemProperty over Set-ItemProperty.
Import-Module WebAdministration
$RecycleTimes = #("00:15", "04:30")
$PrivateMemory = 1468006    
$sites = Get-ChildItem 'IIS:\AppPools\' <# | Where-Object { $_.recycling.periodicRestart.schedule.TotalMilliseconds -gt 1 } #>
    foreach ($s in $sites) {
        # Turn off Fixed Intervals recylcing setting
        Set-ItemProperty $s.PSPath -Name Recycling.periodicRestart.time -Value 0.00:00:00
        # Set application pool recycle time
        Clear-ItemProperty $s.PSPath -Name Recycling.periodicRestart.schedule
        foreach ($RecycleTime in $RecycleTimes) {
            New-ItemProperty $s.PSPath -Name Recycling.periodicRestart.schedule -Value #{value=$RecycleTime}
        }
        #Set Private memory usage
        Set-ItemProperty $s.PSPath -Name recycling.periodicrestart.privateMemory -Value $PrivateMemory
    }
I used the powershell command line code you provided on my local machine and can successfully set two recycle times. This means there is nothing wrong with your code.
You can try to use the following basic powershell command line code to set multiple specific recycling application pool time for the default website, see if it works.
Import-Module WebAdministration
Set-ItemProperty -Path "IIS:\AppPools\DefaultAppPool" -Name Recycling.periodicRestart.schedule -Value #{value="00:15"}
New-ItemProperty -Path "IIS:\AppPools\DefaultAppPool" -Name Recycling.periodicRestart.schedule -Value #{value="04:30"}

Create Application Gateway probe, backend pool, rules ecc.. with powershell New-AzResources

i'm trying to create with powershell and and command new-AzResources some object, like probe, rules etc.. inside an application gateway. I'm using following snippet:
### Get properties
$get = Get-AzResource -ResourceType Microsoft.Network/applicationGateways -Name appgw -ResourceGroupName rgappgw
$user.Properties.probes.Properties
$properties = #{
protocol = 'Http';
path = '/';
interval = '30';
timeout = '30';
unhealthyThreshold = '3';
pickHostNameFromBackendHttpSettings = $true;
minServers = '0';
match = '200-399';
}
$SlotParams = #{
ResourceName = "appGwName"
Location = "West Europe"
ResourceGroupName = "AppGwRg"
ResourceType = "Microsoft.Network/applicationGateways/probes/probename" ####name of probes
PropertyObject = $properties
}
$execution = New-AzResource #SlotParams -Force
but i'm getting following error:
New-AzResource:
Line |
23 | $getSlotApse = New-AzResource #SlotParams -Force
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| {
"Message": "No HTTP resource was found that matches the request URI 'https://westeurope.network.azure.com:30058/123-124-14-4444-4444444/444444444444/subscriptions/mysubs/resourceGroups/AppGwRg/providers/Microsoft.Network/applicationGateways/appGwName/probes/probename?api-version=2022-07-01'."
}
CorrelationId: 12939812312831983
i use same logic to create app service but i'm not understand what i'm doing wrong with application gateway. Can you please give me an advice?
Thanks
I have reproduced in my environment and taken below commands from the Microsoft-Document:
The command or script which you provided are giving errors for me so, I have used below script for creating application gateway.
Firstly, I have created Subnet then Vnet and all the other required resources using below commands:
Update-Module Az.Network
Connect-AzAccount
$subnet = New-AzVirtualNetworkSubnetConfig -Name subnet01 -AddressPrefix 10.0.0.0/24 -WarningAction Ignore
$vnet = New-AzVirtualNetwork -Name appgwvnet -ResourceGroupName "rithwik-resources" -Location 'East US' -AddressPrefix 10.0.0.0/16 -Subnet $subnet
$subnet = $vnet.Subnets[0]
$publicip = New-AzPublicIpAddress -ResourceGroupName "rithwik-resources" -Name publicIP01 -Location 'East US' -AllocationMethod Dynamic
$gipconfig = New-AzApplicationGatewayIPConfiguration -Name rithwikgatewayIP -Subnet $subnet -WarningAction Ignore
$pool = New-AzApplicationGatewayBackendAddressPool -Name pool01 -BackendIPAddresses 134.170.185.46, 134.170.188.221, 134.170.185.50 -WarningAction Ignore
$probe = New-AzApplicationGatewayProbeConfig -Name probe01 -Protocol Http -HostName 'test.com' -Path '/path/path.htm' -Interval 30 -Timeout 120 -UnhealthyThreshold 8 -WarningAction Ignore
$poolSetting = New-AzApplicationGatewayBackendHttpSettings -Name rithwikapps -Port 80 -Protocol Http -CookieBasedAffinity Disabled -Probe $probe -RequestTimeout 80 -WarningAction Ignore
$fp = New-AzApplicationGatewayFrontendPort -Name frontendport01 -Port 80 -WarningAction Ignore
$fipconfig = New-AzApplicationGatewayFrontendIPConfig -Name fipconfig01 -PublicIPAddress $publicip -WarningAction Ignore
$listener = New-AzApplicationGatewayHttpListener -Name listener01 -Protocol Http -FrontendIPConfiguration $fipconfig -FrontendPort $fp -WarningAction Ignore
$rule = New-AzApplicationGatewayRequestRoutingRule -Name rule01 -RuleType Basic -BackendHttpSettings $poolSetting -HttpListener $listener -BackendAddressPool $pool -WarningAction Ignore
$sku = New-AzApplicationGatewaySku -Name Standard_Small -Tier Standard -Capacity 2 -WarningAction Ignore
$appgw = New-AzApplicationGateway -Name appgwtest -ResourceGroupName "rithwik-resources" -Location 'East US' -BackendAddressPools $pool -Probes $probe -BackendHttpSettingsCollection $poolSetting -FrontendIpConfigurations $fipconfig -GatewayIpConfigurations $gipconfig -FrontendPorts $fp -HttpListeners $listener -RequestRoutingRules $rule -Sku $sku -WarningAction Ignore
Output:
Once ran the above commands in powershell then the resources are created in Portal

specified cast is not valid Powershell when changing automatically detect settings and auto config script for LAN settings in Internet Properties

I'm trying to enable and disable the automatically detect settings and automatic configuration script for LAN settings in Internet Explorer(IE). The script is working fine on windows 7 32,64 bit, Windows 10 32,64 bit but on windows 8 64bit it's throwing error specified cast is not valid when disabling the automatically detect settings and enabling/disabling automatic configuration script for LAN settings.
[string]$ProxyRegRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
#this setting is affected by multiple options, so fetch once here
[string]$DefaultConnectionSettingsPath = (Join-Path $ProxyRegRoot 'Connections')
[byte[]]$DefaultConnectionSettings = Get-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' | Select-Object -ExpandProperty 'DefaultConnectionSettings'
[byte]$MaskProxyEnabled = 2
[byte]$MaskUseAutomaticConfigurationScript = 4
[byte]$MaskAutomaticDetect = 8
[int]$ProxyConnectionSettingIndex = 8
#Auto-ConfigScript for LAN Settings
function Auto-ConfigScript {
#region config script
$UseAutomaticConfigurationScriptInput = Read-Host "Enable Automatic Configuration Script [y]Yes [n]No"
if ($UseAutomaticConfigurationScriptInput -eq "yes" -or $UseAutomaticConfigurationScriptInput -eq "y") {
$UseAutomaticConfigurationScript = $true
$UseAutomaticConfigurationScriptAddress = Read-Host "Enter Address "
Set-ItemProperty -Path $ProxyRegRoot -Name AutoConfigURL -Value $UseAutomaticConfigurationScriptAddress
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskUseAutomaticConfigurationScript
}
else {
$UseAutomaticConfigurationScript = $false
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskUseAutomaticConfigurationScript)
}
#endregion
#persist the updates made above
Set-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' -Value $DefaultConnectionSettings
}
function Auto-DetectSettings {
#region auto detect
$AutomaticDetect = Read-Host "Enable Automatically detect settings [y]Yes [n]No"
if ($AutomaticDetect -eq $true -or $AutomaticDetect -eq "yes" -or $AutomaticDetect -eq "y") {
Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 1
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskAutomaticDetect
}
else {
Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 0
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskAutomaticDetect)
}
#endregion
#persist the updates made above
Set-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' -Value $DefaultConnectionSettings
}
Error Traceback
Specified cast is not valid.
At C:\Users\afs.prithvi\Downloads\Internet Properties Win7 32-64 bit working.ps1:23 char:9
+ $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidCastException
+ FullyQualifiedErrorId : System.InvalidCastException
Update
error is occuring at line number 23

Powershell MSUtil.LogQuery not closing SQL connection

I've written a PowerShell scrip that iterates through a large number of IIS W3C logfiles and inserts the values into a MSSQL database.
Set-Variable -Name "UnprocessedDir" -Value "X:\files" -Description "Folder for unprocessed log files" Scope Script
Set-Variable -Name "InputObject" -Value (New-Object -comObject MSUtil.LogQuery.IISW3CInputFormat) -Description "Log Parser input COM object" -Scope Script
Set-Variable -Name "OutputObject" -Value (New-Object -comObject MSUtil.LogQuery.SQLOutputFormat) -Description "Log Parser output COM object" -Scope Script
$OutputObject.clearTable = $false
$OutputObject.createTable = $false
$OutputObject.database = "Database_Name"
$OutputObject.driver = "SQL Server"
$OutputObject.dsn = "DSN_Name"
$OutputObject.fixColNames = $true
$OutputObject.ignoreIdCols = $true
$OutputObject.ignoreMinWarns = $true
$OutputObject.maxStrFieldLen = 511
$OutputObject.oConnString = $null
$OutputObject.password = $null
$OutputObject.server = "sqlserver.domain.com\INSTANCENAME"
$OutputObject.transactionRowCount = 5000
$OutputObject.username = $null
Set-Variable -Name "IISLogs" -Value #(Get-ChildItem -Path $UnprocessedDir -Recurse -File) -Description "Array of files to be imported into SQL" -Scope Script
Set-Variable -Name "LPComObj" -Value (New-Object -com MSUtil.LogQuery) -Description "COM Object used to import Log Parser records into MSSQL" -Scope Script
Write-Output "$(Get-ISOTimeStamp) Beginning SQL import. $($IISLogs.Count) Files to be imported"
$IISLogs | ForEach-Object { $loop = 0 } {
Set-Variable -Name "SubDir" -Value $(($_.FullName).Split('\')[-2]) -Description "Subdirectory where log file is located" -Scope Script
Set-Variable -Name "LogType" -Value $(($_.FullName).Split('\')[-3]) -Description "Type of log being imported" -Scope Script
Set-Variable -Name "ServerName" -Value $(($_.FullName).Split('\')[-4]) -Description "ServerName of file being imported" -Scope Script
Set-Variable -Name "LPQuery" -Description "Query to use in Log Parser" -Scope Script -Value #"
SELECT
-- FIELDS LogFilename,LogRow,date,time,c-ip,cs-username,s-sitename,s-computername,s-ip,s-port,cs-method,cs-uri-stem,cs-uri-query,sc-status,sc-substatus,sc-win32-status,sc-bytes,cs-bytes,time-taken,cs-version,cs-host,cs(User-Agent),cs(Cookie),cs(Referer),s-event,s-process-type,s-user-time,s-kernel-time,s-page-faults,s-total-procs,s-active-procs,s-stopped-procs
-- STANDARD FIELDS date,time,s-ip,cs-method,cs-uri-stem,cs-uri-query,s-port,cs-username,c-ip,cs(User-Agent),cs(Referer),sc-status,sc-substatus,sc-win32-status,time-taken
'$($ServerName)' as [servername],
'$($_.Name)' as [filename],
LogRow AS [row],
'$($LogType)' as [logtype],
TO_TIMESTAMP(date,time) AS [timestamp],
[s-ip],
[cs-method],
[cs-uri-stem],
[cs-uri-query],
TO_INT([s-port]),
[cs-username],
[c-ip],
[cs(User-Agent)],
[cs(Referer)],
TO_INT([sc-status]),
TO_INT([sc-substatus]),
TO_INT([sc-win32-status]),
TO_INT([time-taken]),
0 AS lock
INTO IIS_W3C
FROM '$($_.FullName)'
"#
Set-Variable -Name "LPResult" -Value ($LPComObj.ExecuteBatch($LPQuery, $InputObject, $OutputObject)) -Description "IIS Log File imported into SQL" -Scope Script
If ($LPResult -eq $false)
{
Write-Output "$(Get-ISOTimeStamp) Data imported from `"$($_.FullName)`""
Set-Variable -Name "loop" -Value ($loop + 1) -Description "Increase loop iteration Count" -Scope Script
}
Else
{
Write-Output "$(Get-ISOTimeStamp) Log Parser returned errors importing `"$($_.FullName)`""
Throw "$(Get-ISOTimeStamp) Log Parser returned errors importing `"$($_.FullName)`""
}
}
The number of logs I'm importing is tens of thousands; the code above works spectacularly for a few hundred files, but after a few hours, it crashes. From what I can tell, it looks like every iteration of the ForEach-Object loop creates a new SQL TCP connection which is not terminated at the end of the loop.
I've tried creating the $LPComObj both within and outside of the loop. I've tried Remove-Variable. I've tried some generic commands like $LPComObj.Close(), .Remove(), .Quit(), etc. The MSUtil.LogQuery method itself does not seem to contain any methods to close the SQL TCP connection, and as the script is running, I can see more and more TCP connections piling up. I tried a few things using [System.Runtime.Interopservices.Marshal]:: to release/remove the COM object, but none of them closed the TCP connection. Even closing the PowerShell session doesn't kill the connection.
The only way I was able to do this is by hunting down and finding the dllhost.exe" process that was using the ports and killing it. But from within the script, there isn't a clean way to get the PID of the offending dllhost.exe process. (Trying to kludge some variant of Get-Process | Stop-Process might work, but would add a lot of time to the execution of the script.)
What other ways might I be able to work around this problem?

Automatic site setup with powershell throws several errors

first and foremost I am NOT a Powershell dev so I'm a little over my head here, if this was BASH it would have been done by now....
I'm getting several errors that I don't really understand the what or why of,
I believe that maybe $vars cannot be interpreted in the way that I am trying to use? idk...
If someone WITH powershell knowledge could lend an assist and educate this poor linux guy, I would be very grateful...
I would expect this to register and load a new (empty) site with IIS based of the input params provided.
Here's my PS1
# --------------------------------------------------------------------
# Define the variables.
# --------------------------------------------------------------------
Param (
[string]$InetSiteName = $( Read-Host "Site Name" ),
[int]$InetSitePort = $( Read-Host "Site Port" ),
[string]$InetPhysPath = $( $env:SystemDrive + "\inetpub\wwwroot" )
)
Import-Module "WebAdministration"
# --------------------------------------------------------------------
# Check for empty.
# --------------------------------------------------------------------
if(-not($InetSiteName)) { Throw "Site name cannot be empty..." }
if(-not($InetSitePort)) { Throw "Site port cannot be empty..." }
if(-not($InetPhysPath)) { Throw "Path name cannot be empty..." }
# --------------------------------------------------------------------
# Configure and register.
# --------------------------------------------------------------------
New-Item IIS:\Sites\$InetSiteName -physicalPath $InetPhysPath -bindings #{ protocol="http";bindingInformation=":"+$InetSitePort+":"+$InetSiteName }
Set-ItemProperty IIS:\Sites\$InetSiteName -name applicationPool -value BenAPI
Start-WebSite $InetSiteName
# --------------------------------------------------------------------
# Run.
# --------------------------------------------------------------------
$webclient = New-Object Net.WebClient
$webclient.DownloadString("http://localhost:$InetSitePort/");
$ie = New-Object -com InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate("http://localhost:$InetSitePort/");
This is because "WebAdministration" module is not getting loaded. Run Powershell as Administrator so that "WebAdministration" module gets imported successfully.
Then Go to location where you have saved the script to run the script
PS C:\> cd 'C:\Users\jDaniel\Documents'
PS C:\Users\jDaniel\Documents> .\iis-site.ps1
There is a step to step guide Here - how to create Web-Sites, Web Applications, Virtual Directories and Application Pools in powershell.
This is how I create a new site:
New-WebSite -Name $InetSiteName -port $InetSitePort -id 555 -PhysicalPath "$InetPhysPath" -HostHeader $InetSiteName
if you need more binding you can use:
New-WebBinding -Name $InetSiteName -Port $InetSitePort2 -HostHeader $InetSiteName2
Looks like the real answer was that I didn't have a real pool created, here's my updated code...
Thanks Everyone
# --------------------------------------------------------------------
# Checking Execution Policy
# --------------------------------------------------------------------
#$Policy = "Unrestricted"
$Policy = "RemoteSigned"
If ((get-ExecutionPolicy) -ne $Policy) {
Write-Host "Script Execution is disabled. Enabling it now"
Set-ExecutionPolicy $Policy -Force
Write-Host "Please Re-Run this script in a new powershell enviroment"
Exit
}
# --------------------------------------------------------------------
# Define the variables.
# --------------------------------------------------------------------
[string]$InetSiteName = $( Read-Host "Site Name" )
[int]$InetSitePort = $( Read-Host "Site Port" )
[string]$InetPhysPath = $( $env:SystemDrive + "\inetpub" )
$PoolName = "BenAPI"
# --------------------------------------------------------------------
# Loading IIS Modules
# --------------------------------------------------------------------
Import-Module "WebAdministration"
# --------------------------------------------------------------------
# Test or Create App Pool
# --------------------------------------------------------------------
if (!(Test-Path "IIS:\AppPools\$PoolName" -pathType container))
{
# Create pool
$appPool = New-Item "IIS:\AppPools\$PoolName"
$appPool | Set-ItemProperty -Name "managedRuntimeVersion" -Value "v4.0"
}
# --------------------------------------------------------------------
# Configure and register.
# --------------------------------------------------------------------
$WebRoot = New-Item "$InetPhysPath\$InetSiteName" -type Directory
New-Item IIS:\Sites\$InetSiteName -physicalPath $WebRoot -bindings #{ protocol="http";bindingInformation="*:"+$InetSitePort+":" }
Set-ItemProperty IIS:\Sites\$InetSiteName -name applicationPool -value BenAPI
Set-Content "$WebRoot\default.htm" "Test Page: $InetSiteName"
Start-WebSite $InetSiteName
# --------------------------------------------------------------------
# Run.
# --------------------------------------------------------------------
$ie = New-Object -com InternetExplorer.Application
$ie.Visible = $true
$ie.Navigate("http://localhost:$InetSitePort/");