Quantcast
Channel: Jeong's Blog
Viewing all 23 articles
Browse latest View live

How to use IISAdministration powershell cmdlets to configure IIS configuration settings

$
0
0

FYI, see the below blog first for the detailed information.

https://blogs.iis.net/bariscaglar/iisadministration-powershell-cmdlets-new-feature-in-windows-10-server-2016

 

If you use Configuration Editor, you can make IISPowershell cmdlets more easily. Configuration Editor is a good start point to make IISAdministration powershell script easily.

For example, if you want to add a new appSetting value to Default Web Site, you can generate a code for C# programming with Configuration Editor and you can convert the generated code to IISAdministration powshell cmdles because they are based on the same API.

Here is how to do that:

  1. Open Inetmgr.exe
  2. Select Default Web Site
  3. Go to Configuration Editor page
  4. Expand “Section:” dropdown and select “appSettings”
  5. Click the second column of “(Collection)” listview item
  6. Click “…” button and you will see “Collection Editor” dialog opened
  7. Click “Add” task on the right pane of the “Collection Editor” dialog
  8. Type “test” for the key property and “test2” for the value property and then close the “Collection Editor” dialog
  9. Click “Generate Script” task, and you will get the below code. Click “Cancel” task of Configuration Editor to ignore the change.

using System;

using System.Text;

using Microsoft.Web.Administration;

internal static class Sample {

   private static void Main() {

       using(ServerManager serverManager = new ServerManager()) {

           Configuration config = serverManager.GetWebConfiguration("Default Web Site");

           ConfigurationSection appSettingsSection = config.GetSection("appSettings");

           ConfigurationElementCollection appSettingsCollection = appSettingsSection.GetCollection();          

           ConfigurationElement addElement = appSettingsCollection.CreateElement("add");

             addElement["key"] = @"test";

             addElement["value"] = @"test2";

             appSettingsCollection.Add(addElement);

             serverManager.CommitChanges();

       }

   }

}

Now let’s convert the generated code into IISAdministration powshell cmdlet. Here is the example of the outcome.

Import-Module IISAdministration

Reset-IISServerManager -Confirm:$false

Start-IISCommitDelay

$webConfig = Get-IISConfigSection -SectionPath "appSettings" -CommitPath "Default Web Site"

$collection = Get-IISConfigCollection -ConfigElement $webConfig

New-IISConfigCollectionElement -ConfigCollection $collection -ConfigAttribute @{key='test';value='test2'}

Stop-IISCommitDelay

Remove-Module IISAdministration

 

More examples for your information.

Example 1. Configuring identityType and username together with a new attribute value for computer level.

Import-Module IISAdministration

Reset-IISServerManager -Confirm:$false

Start-IISCommitDelay

$appPoolConfigSection   = Get-IISConfigSection -SectionPath "system.applicationHost/applicationPools"

$appPoolDeefaultsElement = Get-IISConfigElement -ConfigElement $appPoolConfigSection -ChildElementName "applicationPoolDefaults"

$processModelElement     = Get-IISConfigElement -ConfigElement $appPoolDeefaultsElement -ChildElementName "processModel"

Set-IISConfigAttributeValue -ConfigElement $processModelElement -AttributeName "identityType" -AttributeValue "LocalSystem"

$anonymousAuthenticationConfigSection = Get-IISConfigSection -SectionPath "system.webServer/security/authentication/anonymousAuthentication"

Set-IISConfigAttributeValue -ConfigElement $anonymousAuthenticationConfigSection -AttributeName "userName" -AttributeValue ""

Stop-IISCommitDelay

Remove-Module IISAdministration

 

Example 2. Configuring IIS central certificate using IISAdministration

$sharePath = "$env:systemdrive\temp_share"

md $sharePath

 

$certStorePath = "Cert:\LocalMachine\My"

$thumbprint = New-SelfSignedCertificate -DnsName "explicit.one.ccs" -CertStoreLocation $certStorePath

$mypwd = ConvertTo-SecureString -String "xxx" -Force -AsPlainText

Export-PfxCertificate -FilePath "$sharePath\explicit.one.ccs.pfx" -Cert ($certStorePath + "\" + $thumbprint.Thumbprint) -Password $mypwd

 

$PrivateKeyPassword = "xxx"

$user = "administrator"

$passwordSecure = convertto-securestring $PrivateKeyPassword -asplaintext -force

$PrivateKeyPasswordSecure = convertto-securestring $PrivateKeyPassword -asplaintext -force

 

# Enable-IISCentralCertProvider

Enable-IISCentralCertProvider -CertStoreLocation $sharePath -UserName $user -Password $passwordSecure -PrivateKeyPassword $PrivateKeyPasswordSecure

 

Example 3. Configuring IIS Shared configuration

$sharedPath = "$env:systemdrive\temp_share2"

md $sharedPath

$username = "$env:computername\administrator"

$password = convertto-securestring "password1&" -asplaintext -force

$keyEncryptionPassword = convertto-securestring "password2&" -asplaintext -force

Export-IISConfiguration -UserName $username -Password $password -PhysicalPath $sharedPath -KeyEncryptionPassword $keyEncryptionPassword -force

Enable-IISSharedConfig -UserName $username -Password $password -PhysicalPath $sharedPath -DontCopyRemoteKeys

NOTE:
If you run into the below error, you can fix the problem with installing the latest .Net runtime such as 4.6.1.

... Export-IISConfiguration : Method not found: '!!0[] System.Array.Empty()'.  ...   
... Get-IISSharedConfig : Method not found: 'System.String ...

Example 4. Create a new web site with a SSL Binding

New-IISSite -Name "TestSite" -PhysicalPath "$env:systemdrive\inetpub\testsite" -BindingInformation "*:443:" -CertificateThumbPrint "D043B153FCEFD5011B9C28E186A60B9F13103363" -CertStoreLocation "Cert:\LocalMachine\Webhosting" -Protocol https

Example 5. Add a SSL Binding to the Default Web Site

New-IISSiteBinding -Name "TestSite" -BindingInformation "*:443:" -CertificateThumbPrint "D043B153FCEFD5011B9C28E186A60B9F13103363" -CertStoreLocation "Cert:\LocalMachine\Webhosting" -Protocol https

Example 6. Create a new WebSite with creating a new application pool

Reset-IISServerManager -Confirm:$false
Start-IISCommitDelay
$sm = Get-IISServerManager
$sm.ApplicationPools.Add("TestSite")
New-IISSite -Name Test -PhysicalPath C:\inetpub\wwwroot -BindingInformation "*:1234:"
$sm.Sites["Test"].Applications["/"].ApplicationPoolName = "TestSite"
$sm.CommitChanges()
Stop-IISCommitDelay


IIS URL Rewrite - one of known issues with the rewriteBeforeCache feature

$
0
0

I ran into IIS worker process (w3wp.exe) crash issue under specific conditions:

  1. If IIS apppool is running in the Classic mode
  2. ExtensionlessUrlHandler is configured
  3. IIS Url Rewrite outbound rule is configured with enabling with setting rewriteBeforeCache="true".

After investigating the issue to avoid the crash issue, I find one recommended workaround of the issue.  

Because the crash issue happens under those conditions, there are various workaround ways like this:

  1. If we use Integrated Mode instead of the Class mode, there is no issue.
  2. Or, if we remove the ExtensionlessUrlHandler modules, the issue is also fixed even though the classic mode is being used.
  3. Finally, if we disable the rewriteBeforeCache feature, the issue can be solved as well even though we keep using the Classic mode and the ExtensionlessUrlHandler module. 

NOTE

  1. If rewriteBeforeCache is enabled, URL Rewrite's outbound rule won't be applied for the extensionless requests because the ExtensionlUrlHandler sends the response ealier than Url Rewrite module. If you want to apply the outbound URL Rewrite rule to the extensionless requests as well, you should consider disabling the rewriteBeforeCache feature.
  2. If rewriteBeforeCache is disabled, there can be some performance penalty. So, you should make optimized Url Rewrite outboud rules to avoid high CPU usage.

In my opinion, disabling the rewriteBeforeCache feature is the simplest (not causing any functional change) workaround way in order to avoid the crash issue.

So, here I'd like to sho the way about how to disable the rewriteBeforeCache feature.

Considering the fact that the default attribute value of the rewriteBeforeCache is "false", you can disable the feature with changing the IIS Url Rewrite ouboundRule section as the following:

    <rewrite>

        <outboundRules>

        ...

- Or -

    <rewrite>

        <outboundRules rewriteBeforeCache="false">

        ...

How to use the IIS Insider docker tag

$
0
0

I'd like to explain the basic usage of the microsoft-windows-servercore-iis-insider docker tag so that you can use it easily.

In addition, I want to introduce a new feature, which is currently available with the insider version of IIS docker tag.

The new feature is to make the docker log from IIS ETW logging so that you can get the IIS activity that is happenning inside of the docker container immediately.

Once you understand about how to use the new feature, you will also want to try the new feature with the other existing IIS tags and that is possible with making your own Dockerfile.

I have explained about how to apply the new feature with the existing iis tags as well here.

 

The new feature is powered by using the logmonitor.exe with a predefined LogMonitorConfig.json in order to expose the IIS Etw logging to the logmonitor.exe.

If you want to include other data, you can customze LogMonitorConfig.json, referring to the LogMonitor instruction.

 

How to use the IIS Insider tag

1. Prepare a docker host machine referring to the microsoft-windows-servercore-insider instruction

NOTE: The current latest IIS insider tag is compatible to windowsservercore-10.0.19035.1

2. Run a IIS docker with running

docker run --name TestIisInsider --interactive --tty --rm --publish 5000:80 mcr.microsoft.com/windows/servercore/iis/insider:windowsservercore-10.0.19035.1

 

- Or -

 

docker run -n TestIisInsider -i -t --rm -p 5000:80 mcr.microsoft.com/windows/servercore/iis/insider:windowsservercore-10.0.19035.1

NOTE:

  • mcr.microsoft.com/windows/servercore/iis/insider:windowsservercore-10.0.19035.1
    This is the IIS Insider tag name. With the tag name, you can notice that it is made from a certain version (10.0..19351.1) of the windowsservcore insider tags
  • --name TestIisInsider
    This allows to set the docker id with "TestIisInsider" for the new docker container. This is optional if you don't use the docker id later.
  •  --interactive and --tty
    This allows to send the docker control signals such as Ctrl-C. If you don't need to use the control signal, you don't need to specify these docker options
  • --rm
    This is to remove the docker container automatically when it is stopped. If you don't want to remove the docker container, you don't need to specify the docker option
  • --publish 5000:80
    This is to publish the tcp port 5000 of the host machine and map to the tcp port 50 of the docker container. If you want to use other port, you can adjust the port values

 

3. Open a web browser and send a request http://localhost:5000

4. If everything works, you will get the response from the Default Web Site of the newly created docker container and the console of the docker client will show the IIS ETW event log as the following example:

C:\> docker run --interactive --tty --rm -p 5000:80 mcr.microsoft.com/windows/servercore/iis/insider:windowsservercore-10.0.19035.1

 

<Source>EtwEvent</Source><Time>2020-02-03T19:44:22.000Z</Time><Provider idGuid="{7E8AD27F-B271-4EA2-A783-A47BDE29143B}"/

><DecodingSource>DecodingSourceXMLFile</DecodingSource><Execution ProcessID="8092" ThreadID="8792" /><Level>Information<

/Level><Keyword>0x8000000000000000</Keyword><EventID Qualifiers="6200">6200</EventID><EventData><EnabledFieldsFlags>2478

079</EnabledFieldsFlags><date>2020-02-03</date><time>19:44:19</time><c-ip>10.121.100.145</c-ip><cs-username>-</cs-userna

me><s-sitename>W3SVC1</s-sitename><s-computername>1b1ccba0391d</s-computername><s-ip>172.18.164.253</s-ip><cs-method>GET

...

<sc-substatus>0</sc-substatus><CustomFields></CustomFields></EventData>


 5. In order to stop the IIS docker, you can type Ctrl-C from the console of the docker client and you will see the docker container is stopped automatically with the below log information.

CTRL signal received. The process will now terminate.

[2020-02-03T19:53:56.000Z][LOGMONITOR] INFO: Entrypoint processs exit code: -1073741510

NOTE:

  • You can also stop the IIS insider docker container with stopping the w3svc service with running "net stop w3svc" command as the following:

C:\> docker exec TestIisInsider net stop w3svc

The World Wide Web Publishing Service service is stopping.

The World Wide Web Publishing Service service was stopped successfully.

  

How to use the new feature with the existing IIS tags

In order to use the new feature with other existing IIS tags, you can simply update your docker file with referring to the dockerfile of the IIS Insider tag: https://raw.githubusercontent.com/microsoft/iis-docker/master/windowsservercore-insider/Dockerfile

Here is one example of the Dockerfile to enable the new feature to the existing mcr.microsoft.com/windows/servercore/iis docker tag.

# escape=`

 

FROM mcr.microsoft.com/windows/servercore/iis

 

# Install LogMonitor.exe and upgrade the ServiceMonitor.exe with the newer version

RUN powershell -Command `

    Add-WindowsFeature Web-Server; `

    New-Item -ItemType Directory C:\LogMonitor; `

    $downloads = `

    @( `

        @{ `

            uri = 'https://dotnetbinaries.blob.core.windows.net/servicemonitor/2.0.1.8/ServiceMonitor.exe'; `

            outFile = 'C:\ServiceMonitor.exe' `

        }, `

        @{ `

            uri = 'https://github.com/microsoft/windows-container-tools/releases/download/v1.1/LogMonitor.exe'; `

            outFile = 'C:\LogMonitor\LogMonitor.exe' `

        }, `

        @{ `

            uri = 'https://raw.githubusercontent.com/microsoft/iis-docker/master/windowsservercore-insider/LogMonitorConfig.json'; `

            outFile = 'C:\LogMonitor\LogMonitorConfig.json' `

        } `

    ); `

    $downloads.ForEach({ Invoke-WebRequest -UseBasicParsing -Uri $psitem.uri -OutFile $psitem.outFile })

 

# Change the startup type of the IIS service from Automatic to Manual

RUN sc config w3svc start=demand

 

# Enable ETW logging for Default Web Site on IIS

RUN c:\windows\system32\inetsrv\appcmd.exe set config -section:system.applicationHost/sites /"[name='Default Web Site'].logFile.logTargetW3C:"File,ETW"" /commit:apphost

 

EXPOSE 80

 

# Start "C:\LogMonitor\LogMonitor.exe C:\ServiceMonitor.exe w3svc"

ENTRYPOINT ["C:\\LogMonitor\\LogMonitor.exe", "C:\\ServiceMonitor.exe", "w3svc"]

  

Viewing all 23 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>