RU EN
сегодня

Automating ASP.NET Core 9.0 deployment with a PowerShell script

Automating ASP.NET Core 9.0 deployment with a PowerShell script
Автор:
Источник:
Просмотров:
59
Automating ASP.NET Core 9.0 deployment with a PowerShell script favorites 0

Deploying an ASP.NET Core 9.0 application manually can be a time-consuming and error-prone process. To streamline this, I’ve created a PowerShell script that automates the deployment of a .NET Core web application to an IIS server. This ensures minimal downtime while making the process efficient and repeatable.

Overview of the deployment script

This PowerShell script automates key deployment tasks:
→ Publishes the ASP.NET Core 9.0 application.
→ Puts the application into maintenance mode.
→ Stops the IIS Application Pool before deployment.
→ Replaces old files with the new version.
→ Restarts the Application Pool and removes maintenance mode.
→ Opens the application in a browser after deployment.

• • •

Step-by-Step breakdown of the script

1. Define paths and variables

The script starts by setting up key paths such as:
Project directory: The location of the source code.
Publish directory: Where the application will be published.
IIS deployment path: The live website directory.
Application Pool name: The name of the IIS app pool.

# Define variables
# Set base project directory (relative to script location)
$basePath = $PSScriptRoot
$projectPath = Join-Path $basePath ".\Presentation\HRMSuite.Web"
$publishPath = Join-Path $basePath ".\HRMSuite.Web.Publish"
$websitePath = "C:\inetpub\wwwroot\hrms"
$appPoolName = "hrms"
$appOfflineFile = "$websitePath\app_offline.htm"  # Path to the app_offline file

# Stop script execution on error
$ErrorActionPreference = "Stop"

2. Enable maintenance mode

Before deployment, we notify users about the update by creating an app_offline.htm file in the IIS directory.

# Create app_offline.htm to inform users of update (like in the batch script)
Write-Host "Creating app_offline.htm file..." -ForegroundColor Yellow
$offlineContent = "System Update in Progress, please refresh after 2-3 minutes..."
Set-Content -Path $appOfflineFile -Value $offlineContent

This ensures that users see a maintenance message instead of encountering errors during deployment.

3. Publish the application

The script then compiles and publishes the application in release mode to the specified folder.

# Publish the .NET application
dotnet publish "$projectPath" -c Release -o "$publishPath" --self-contained false --nologo --verbosity quiet /p:NoWarn="CS8618;CS8600"

Using --self-contained false reduces the package size by relying on an existing .NET runtime on the server.

4. Stop the IIS Application Pool

Before replacing old files, we ensure that the application is not running by stopping the IIS App Pool.

# Get the application pool state
$appPoolState = (Get-WebAppPoolState -Name $appPoolName).Value

# Stop the App Pool only if it's running
if ($appPoolState -eq "Started") {
    Write-Host "Stopping IIS Application Pool: $appPoolName" -ForegroundColor Yellow
    Stop-WebAppPool -Name $appPoolName
} else {
    Write-Host "Application Pool '$appPoolName' is already stopped." -ForegroundColor Cyan
}

5. Replace old files with new deployment

After stopping the application, the script deletes old files (excluding logs and app_offline.htm).

# Remove existing files in IIS folder (but skip app_offline.htm and logs folder)
Write-Host "Removing old deployment files..." -ForegroundColor Red
Get-ChildItem -Path $websitePath -Exclude "app_offline.htm", "logs" | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue

Then, it copies the new published files to the IIS directory using Robocopy.

# Copy new published files
Write-Host "Copying new files to IIS directory..." -ForegroundColor Green
Robocopy $publishPath $websitePath /E /NFL /NDL /njh /njs /np /XO /XF .gitkeep

6. Restart the Application Pool

Once the new files are in place, the IIS App Pool is restarted.

# Start IIS Application Pool
Write-Host "Starting IIS Application Pool: $appPoolName" -ForegroundColor Yellow
Start-WebAppPool -Name $appPoolName

7. Remove maintenance mode

After deployment, app_offline.htm is removed so that the site can go live.

# Remove app_offline.htm after successful deployment
# Check if app_offline.htm exists before removing
if (Test-Path -Path $appOfflineFile) {
    Write-Host "Removing app_offline.htm after deployment..." -ForegroundColor Yellow
    Remove-Item -Path $appOfflineFile -Force
} else {
    Write-Host "app_offline.htm file not found, skipping removal." -ForegroundColor Cyan
}

8. Open the website

Finally, the script automatically opens the application in a web browser.

# Open the website immediately after deployment
$websiteUrl = "http://localhost"
Write-Host "Opening the website: $websiteUrl" -ForegroundColor Green
Start-Process $websiteUrl

• • •

PowerShell deployment script

Below is a PowerShell script that automates the deployment process:

# Define variables
# Set base project directory (relative to script location)
$basePath = $PSScriptRoot
$projectPath = Join-Path $basePath ".\Presentation\HRMSuite.Web"
$publishPath = Join-Path $basePath ".\HRMSuite.Web.Publish"
$websitePath = "C:\inetpub\wwwroot\hrms"
$appPoolName = "hrms"
$appOfflineFile = "$websitePath\app_offline.htm"  # Path to the app_offline file

# Stop script execution on error
$ErrorActionPreference = "Stop"

Write-Host "Publishing ASP.NET Core 9.0 Application..." -ForegroundColor Cyan

# Create app_offline.htm to inform users of update (like in the batch script)
Write-Host "Creating app_offline.htm file..." -ForegroundColor Yellow
$offlineContent = "System Update in Progress, please refresh after 2-3 minutes..."
Set-Content -Path $appOfflineFile -Value $offlineContent

# Publish the .NET application
dotnet publish "$projectPath" -c Release -o "$publishPath" --self-contained false --nologo --verbosity quiet /p:NoWarn="CS8618;CS8600"

# Get the application pool state
$appPoolState = (Get-WebAppPoolState -Name $appPoolName).Value

# Stop the App Pool only if it's running
if ($appPoolState -eq "Started") {
    Write-Host "Stopping IIS Application Pool: $appPoolName" -ForegroundColor Yellow
    Stop-WebAppPool -Name $appPoolName
} else {
    Write-Host "Application Pool '$appPoolName' is already stopped." -ForegroundColor Cyan
}

# Remove existing files in IIS folder (but skip app_offline.htm and logs folder)
Write-Host "Removing old deployment files..." -ForegroundColor Red
Get-ChildItem -Path $websitePath -Exclude "app_offline.htm", "logs" | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue

# Copy new published files
Write-Host "Copying new files to IIS directory..." -ForegroundColor Green
Robocopy $publishPath $websitePath /E /NFL /NDL /njh /njs /np /XO /XF .gitkeep

# Start IIS Application Pool
Write-Host "Starting IIS Application Pool: $appPoolName" -ForegroundColor Yellow
Start-WebAppPool -Name $appPoolName

# Remove app_offline.htm after successful deployment
# Check if app_offline.htm exists before removing
if (Test-Path -Path $appOfflineFile) {
    Write-Host "Removing app_offline.htm after deployment..." -ForegroundColor Yellow
    Remove-Item -Path $appOfflineFile -Force
} else {
    Write-Host "app_offline.htm file not found, skipping removal." -ForegroundColor Cyan
}

# Open the website immediately after deployment
$websiteUrl = "http://localhost"
Write-Host "Opening the website: $websiteUrl" -ForegroundColor Green
Start-Process $websiteUrl

Write-Host "Deployment Completed Successfully!" -ForegroundColor Green

• • •

Conclusion

Automating deployment with PowerShell makes the process smooth, predictable, and efficient. This script can be further enhanced with logging and rollback mechanisms. If you’re working with ASP.NET Core and IIS, this deployment script can significantly simplify your workflow.

Happy coding & deploying!

Похожее
Dec 23, 2023
Author: Juldhais Hengkyawan
This article will teach us how to retrieve the client’s IP address and location information in ASP.NET Core web development. Retrieve the client IP from HttpContext In ASP.NET Core, you can easily get the client IP address from the HttpContext...
Aug 12, 2024
Author: Crafting-Code
Containerizing and deploying ASP.NET Core applications Containerization has transformed the way applications are developed, deployed, and managed in the modern software industry. Docker, in particular, has become a pivotal tool, simplifying the packaging and deployment of applications, including ASP.NET Core...
Jul 9, 2023
Author: Kenji Elzerman
When you have multiple applications and they need to communicate with each other to exchange data you might want to use a protocol that makes something like that happen. In C#, the HTTPClient class provides a powerful and flexible way...
Apr 15, 2024
Author: Olorundara Komolafe
Scheduling one or more background tasks is almost inevitable when building robust, self-sustaining APIs with .NET. A few packages have been around for years, such as Hangfire and Quartz.NET. ASP.NET Core allows background tasks to be implemented as hosted services....
Написать сообщение
Тип
Почта
Имя
*Сообщение
RSS
Если вам понравился этот сайт и вы хотите меня поддержать, вы можете
Функции и хранимые процедуры в PostgreSQL: зачем нужны и как применять в реальных примерах
Вопросы с собеседований, которые означают не то, что вы думаете
Микросервисы (Microservices)
Soft skills: 18 самых важных навыков, которыми должен владеть каждый работник
Что такое технический долг и как им управлять
Вайб-кодинг: программисты нашли способ зарабатывать, ничего не делая?
Топ 20 ботов которые постоянно сканируют ваши сайты. Не все из них одинаково полезны
Grafana: Погружение в мир данных и визуализации
Компиляция и запуск C# и Blazor внутри браузера
Почему сеньоры ненавидят собеседования с кодингом, и что компании должны использовать вместо них
Boosty
Donate to support the project
GitHub account
GitHub profile