Welcome to my blog!

Powershell & IIS

March 26, 2021 23:20

Powershell & IIS (edit)

1) Tìm đường dẫn của MSBuild.exe

Tìm đường dẫn của MSBuild.exe? Vào Powershell, gõ lệnh sau:

&"${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe

Tìm đường dẫn của devenv.exe hoặc Installer\setup.exe? Vào Powershell, gõ lệnh sau:

&"${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -products *

2) Dùng MSBuild để BUILD & DEPLOY ứng dụng ASP.NET hoặc ASP.NET Core

Using command-line MSBuild tool to build .Net Project/Solution | Sparekh (HAY)

Build and Deploy using MSBuild command-line tool | Sparekh (HAY)

Use MSBuild.exe to build specific targets in solutions - Visual Studio | Microsoft Docs

MSBuild publish dotnet core application - Stack Overflow (HAY)

Build a solution:

msbuild  NameOfYourSoution.sln

Build a specific project

msbuild NameOfYourProject.csproj

The project could be c# or vb or any other .Net compatible project.

Both of the above commands will build a debug version of your solution/project. What if you want to specify  Release Configuration or other Configuration you created?

This can be easily handled with MSBuild properties arguments.

Specifying MSBuild Configuration parameter:

msbuild NameOfYourProject.csproj /p:Configuration=Release

Rebuilding your project with MSBuild command-line

This can be achieved with /t: argument where t stands for Targets

msbuild NameOfYourProject.csproj /t:rebuild

Cleaning your Solution/Project with MSBuild command-line

msbuild NameOfYourSolution.sln /t:clean

Build & Deploy 

Here is the all-in one Build and Deploy msbuild command. You can extend it to your liking by adding more parameters.

msbuild YourProject.csproj /P:Configuration=Release /P:DeployOnBuild=True /P:DeployTarget=MsDeployPublish /P:MsDeployServiceUrl=https://yourserver-address/msdeploy.axd /P:AllowUntrustedCertificate=True /P:MSDeployPublishMethod=WMSvc /P:CreatePackageOnPublish=True /P:UserName=username /P:Password=password /P:DeployIISAppPath="yoursite.com" 


3) Deploy using public profiles

Visual Studio publish profiles (.pubxml) for ASP.NET Core app deployment | Microsoft Docs

Visual Studio publish profiles for ASP.NET Core app deployment

VS_Publish_Profiles_1.1.pdf (windows.net)

Guide to use the dotnet publish

docs/dotnet-publish.md at main · dotnet/docs · GitHub

Publish on Azure DevOps

Publish a self-contained .NET Core 3.1 app on Azure DevOps | elmah.io

4) Dùng PowerShell để tạo Website trong IIS (Web Server)

https://octopus.com/blog/iis-powershell (HAY HAY HAY)





Import-Module WebAdministration
Set-Location IIS:\AppPools\


$Folder = New-Item C:\inetpub\wwwroot\test –ItemType directory
$Website = New-Website -Name "test" -Port 80 -PhysicalPath $Folder -ApplicationPool DefaultAppPool
Set-ItemProperty 'IIS:\Sites\test' applicationPool DefaultAppPool

Give specific local Windows user group full control access to a folder and its sub folders (IIS_IUSRS + IUSR)

September 6, 2020 23:07

Give specific local Windows user group full control access to a folder and its sub folders (edit)

Application Pool Identities | Microsoft Docs





  • IIS_IUSRS (build-in group in IIS 7.0)
  • IUSR (build-in account in IIS 7.0)
  • IIS AppPool\DefaultAppPool


Application Pool Identities - Full Access from IIS - Web Deploy - Deployment (HAY HAY HAY HAY HAY)

using System.IO;
using System.Security.AccessControl;

namespace GiveFullPermissionToFolder
class Program
private static void Main(string[] args)
string path = @"C:\Deploy";

DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

//var groupName_IIS_IUSRS = Environment.MachineName + @"\IIS_IUSRS";

//var groupName = @"IIS AppPool\DefaultAppPool";
//var groupName = @".\IIS_IUSRS";
//var groupName = @".\Users";
//var groupName = @"IUSR";
//var groupName = @"Authenticated Users";

var groupNames = new[]
@"IIS AppPool\DefaultAppPool",
@"Authenticated Users"

foreach (var groupName in groupNames)

new FileSystemAccessRule(groupName,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,



How to give full permission to a folder

using System;
using System.IO;
using System.Security.AccessControl;

namespace Secure
internal class Program
private static void Main(string[] args)
string path = @"D:\Samples\WebService";

DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

var groupName_IIS_IUSRS = Environment.MachineName + @"\IIS_IUSRS";
var groupName = @".\IIS_IUSRS";

new FileSystemAccessRule(groupName,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,



Using AppCmd.exe to Create Site in IIS

September 3, 2020 21:39

Using AppCmd.exe to Create Site in IIS (edit)






cd %windir%\system32\inetsrv


AppCmd.exe /?


AppCmd.exe ADD SITE /name:WebApp01 /physicalPath:"C:\Inetpub\wwwroot\WebApp01" /bindings:https/*:44301:WebApp01
AppCmd.exe SET SITE /site.name:WebApp01 /[path='/'].applicationPool:DefaultAppPool

AppCmd.exe ADD SITE /name:WebApp02 /physicalPath:"C:\Inetpub\wwwroot\WebApp02" /bindings:https/*:44302:
AppCmd.exe SET SITE /site.name:WebApp02 /[path='/'].applicationPool:DefaultAppPool

AppCmd.exe ADD SITE /name:WebApp03 /physicalPath:"C:\Inetpub\wwwroot\WebApp03" /bindings:https/*:44303:
AppCmd.exe SET SITE /site.name:WebApp03 /[path='/'].applicationPool:DefaultAppPool

ADD & SET in a single line

mkdir C:\inetpub\wwwroot\WebApp04

AppCmd.exe add site /name:WebApp04 /physicalpath:"C:\inetpub\wwwroot\WebApp04" & AppCmd.exe set config -section:system.applicationHost/sites /+"[name='WebApp04'].bindings.[protocol='https',bindingInformation='']" /commit:apphost

ADD & SITE Program

https://drive.google.com/file/d/10IJrgUf3dZ5mso66LwkOVRnnR-ohh1Zf/view?usp=sharing (manhng83@gmail.com)

using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace WindowsFormsApp3
    public partial class Form1 : Form
        public Form1()
        private void btnCreateSite_Click(object senderEventArgs e)
            string strSite = txtSite.Text.Trim();
            string strPhysicalPath = txtPhysicalPath.Text.Trim();
            string strIpAddress = txtIpAddress.Text.Trim();
            string strPort = txtPort.Text.Trim();
            string strHost = txtHost.Text.Trim();
            if (!System.IO.Directory.Exists(strPhysicalPath))
            string strAppCmdLocation = Environment.ExpandEnvironmentVariables("%windir%\\system32\\inetsrv\\appcmd.exe");
            if (System.IO.File.Exists(strAppCmdLocation))
                string strCmdParams = strAppCmdLocation + string.Format(" add site /name:{0} /physicalpath:\"{1}\" & {2} set config -section:system.applicationHost/sites /+\"[name = '{0}'].bindings.[protocol = 'https', bindingInformation = '{3}:{4}:{5}']\" /commit:apphost"strSitestrPhysicalPathstrAppCmdLocationstrIpAddressstrPortstrHost);
                System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd""/c " + strCmdParams);
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.UseShellExecute = false;
                procStartInfo.CreateNoWindow = true;
                procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                string result = proc.StandardOutput.ReadToEnd();
        private void Form1_Load(object senderEventArgs e)
            txtSite.Text = "WebApp9";
            txtPhysicalPath.Text = @"C:\inetpub\wwwroot\WebApp9";
            txtIpAddress.Text = "";
            txtPort.Text = "443";
            txtHost.Text = "";

LIST SITE to the XML file

AppCmd.exe list site "MySite" /config /xml > "C:\Users\Administrator\Desktop\MySite.xml"

Deploy IIS

October 16, 2018 08:56

Deploy IIS (edit)



1) The IIS Admin Service


2) World Wide Web Publishing Service


Deployment of a Website on IIS

Application Pools on IIS 6.0

Deploying ASP.NET Websites on IIS 7.0

How To Deploy a Web App in IIS

Recycle Application Pool(s) in IIS 7 Server Using C# Code

Windows XP IIS Manager v1.7

Programmatically Manage IIS

Use C# to manage IIS

Beginner's Guide: Exploring IIS 6.0 With ASP.NET

Windows Service Management

Controlling installed services via ServiceController in WinForms

Using NET STOP and NET START commands to force IIS services to re-read the registry


Common IIS-related services

Service Name Display Name
Iisadmin IIS Admin Service
Msftpsvc FTP Publishing Service
Nntpsvc Microsoft NNTP Service
Smtpsvc Microsoft SMTP Service
W3svc World Wide Web Publishing Service

(c) Microsoft Corporation 2000, All Rights Reserved. Contributions by Kevin Zollman, Microsoft Corporation.


3) Add Website


You can add a website using Add method that is present in the Sites collection of ServerManager. Below is the code snippet which creates an application Pool, and then creates a site, also enables the FREB and commit the changes to the IIS7 configuration file:

ServerManager serverMgr = new ServerManager();
Site mySite = serverMgr.Sites.Add("MySiteName", "C:\\inetpub\\wwwroot", 8080);
mySite.ApplicationDefaults.ApplicationPoolName = "MyAppPool";
mySite.TraceFailedRequestsLogging.Enabled = true;
mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";

Now, let's try to delete the same website created. As you know earlier, in IIS7, you need to give an unique name for each website (which was not the case in IIS 6.0).

Site site = serverMgr.Sites["MySiteName"]; // you can pass the site name or the site ID



4) Command Lines


IIS + System.DirectoryServices + Use C# to manage IIS + IIS Manager

October 10, 2018 22:23

Use C# To Manage IIS - Using System.DirectoryServices namespace (edit)


Use C# to manage IIS


Programmatically Manage IIS


Windows XP IIS Manager v1.7


Need to install the "IIS Metabase and IIS 6 configuration compatibility 

Read more: https://drive.google.com/file/d/19G0_FwXX-odXPnXTk6jVBWCipBODFZdV/




Creating Web API in ASP.NET Core 2.0


Xcopy + Appcmd + Cacls + iCacls

October 9, 2018 21:58

iCACLS.exe (edit)



List files and their permissions (access) in command line: 

iCACLS C:\inetpub\wwwroot\Sites\Site1

How to reset NTFS permissions with iCACLS


iCACLS (link)

c:\windows\system32\icacls c:\folder /grant "domain\user":(OI)(CI)M c:\windows\system32\icacls c:\folder /grant "everyone":(OI)(CI)M c:\windows\system32\icacls c:\folder /grant "Authenticated Users":(OI)(CI)M

icacls systax for recursively adding permissions for Administrators to a folder without altering existing permissions?

icacls "<root folder>" /grant "Domain Admins":F /t

would add Full Access to the "Domain Admins" group to the "root folder" and every folder within.

If you add ":r" after Grant then the permissions would be replaced instead of being added.

icacls "<root folder>" /grant:r "Domain Admins":F /t

The basic permissions are:

Full Control (F)

Modify (M)

Read & Execute (RX)

List Folder Contents (X,RD,RA,REA,RC)

Read (R)

Write (W)

Advanced permissions are:

Full Control (F)

Traverse folder / execute file (X)

List folder / read data (RD)

Read attributes (RA)

Read extended attributes (REA)

Create file / write data (WD)

Create folders / append data (AD)

Write attributes (WA)

Write extended attributes (WEA)

Delete subfolders and files (DC)

Delete (D)

Read permissions (RC)

Change permissions (WDAC)

Take ownership (WO)

You can also specify the inheritance for the folders:

This folder only

This folder, subfolders and files (OI)(CI)

This folder and subfolders (CI)

This folder and files (OI)

Subfolders and files only (OI)(CI)(NP)(IO)

Subfolders only (CI)(IO)

Files only (OI)(IO)


xcopy /s /y "C:\inetpub\wwwroot\Sites\Site1\*.*" "D:\Sites\Site1\"


xcopy /S /Q /Y /F    "C:\inetpub\wwwroot\Sites\Site1" "D:\Sites\Site1"
xcopy /S /Q /Y /F    "C:\inetpub\wwwroot\Sites\Site1" "D:\Sites\Site1"
xcopy /S /I /Q /Y /F "C:\inetpub\wwwroot\Sites\Site1" "D:\Sites\Site2"
xcopy /S /I /Q /Y /F "C:\inetpub\wwwroot\Sites\Site1" "D:\Sites\Site2"

/E - Copies folders and subfolders, including empty ones. 
/H - Copies hidden and system files also. 
/K - Copies attributes. Typically, Xcopy resets read-only attributes.
/O - Copies file ownership and ACL information.
/X - Copies file audit settings (implies /O).

/X - Copies file audit settings and system access control list (SACL) information (implies /o).
/O - Copies file ownership and discretionary access control list (DACL) information.

/X – Copies file audit settings and file ownership and ACL information.
/H – Copies hidden and system files.
/E – Copies directories and subdirectories, including empty ones.
/V – Verifies each new file.
/D – Copies files changed on or after the specified date (D:m-d-y).If no date is given, copies only those files whose source time is newer than the destination time.
/Y – Suppresses prompting to confirm you want to overwrite an existing destination file.

Windows Server 2016

  • Windows Server 2016
  • IIS 10 (Windows 10 and Windows Server 2016)
  • MS SQL Server 2017
  • Office 365 Account
5.0 Built-in component of Windows 2000. Windows 2000
5.1 Built-in component of Windows XP Professional. Windows XP Professional
6.0 Built-in component of Windows Server 2003. WIndows Server 2003
7.0 Built-in component of Windows Vista and Windows Server 2008. Windows Vista and WIndows Server 2008
7.5 Built-in component of Windows 7 and Windows Server 2008 R2. Windows 7 and Windows Server 2008 R2
8.0 Built-in component of Windows 8 and Windows Server 2012. Windows 8 and Windows Server 2012
8.5 Built-in component of Windows 8.1 and Windows Server 2012 R2. Windows 8.1 and Windows Server 2012 R2
10.0 Built-in component of Windows 10 and Windows Server 2016. Windows 10 and Windows Server 2016

IIS version?


Windows Server 2016 Security Guide







Typically, each of these commands would be used with an object type that you are asking AppCmd.exe to perform the requested function on.

Possibilities of the object type are:

  • Site – IIS virtual site
  • App – IIS application
  • Vdir – IIS virtual directory
  • Apppool – IIS application pool
  • Config – IIS general configuration
  • Backup – IIS server configuration backups (and the restore command is also available)
  • Wp – IIS worker processes
  • Request – active HTTP requests
  • Module – IIS server administration modules
  • Trace – IIS server trace logs


AppCmd is the built-in CLI tool for configuring and managing IIS. You can use it to create sites and app pools, link virtual directories, and edit configurations. Let’s look at a few things it can do.

First of all, add %systemroot%\system32\inetsrv\ to your path so that you can run appcmd from a command prompt in any location.

Run the command prompt as administrator.

setx PATH "%PATH%;%systemroot%\system32\inetsrv\"


Try the following commands to explore appcmd:

  • Run appcmd /? to see the help text
  • See what apps are running with appcmd list app
  • Use appcmd list backup to see backups of your IIS config

Add site

appcmd add site /name:"Dummy Site" /id:10 /bindings:http/*:81:

Now list apps again. You won’t see the new site you’ve added because it isn’t considered an app. If you go to the GUI and refresh your sites, you’ll see the new site there, but it’ll be broken. We need to add an app using appcmd.

appcmd add app /site.name:"Dummy Site" /path:"/"

This will only add the app to the site at the root. It will create an app named “Dummy Site/”. We still need to link the app to a virtual directory then point that to a physical path.

appcmd add vdir /app.name:"Dummy Site/" path:"/"

appcmd set vdir "Dummy Site/" /physicalPath:"c:\inetpub\wwwroot"

This is the verbose way to use appcmd to create an IIS site. There’s an easier way.

The EZ way

You can save a lot of keystrokes while creating the site if you set the physicalPath parameter in the first command. This will do the whole thing in one shot:

appcmd add site /name:"Dummy Site" /id:10 /bindings:http/*:81: /physicalPath:"c:\inetpub\wwwroot"

But knowing the other commands gives you a better idea of how an IIS app really works under the hood. In the past, I’ve used appcmd in the post-build script of ASP.NET proj files to ensure the site was set up locally on new developer machines. You can also do a backup and restore of IIS config using appcmd.

Deploying updates

To give you one more idea about using appcmd, consider doing the following:

  1. Create a “sites” folder.
  2. Create a subfolder for each site.
  3. Deploy versions to subfolders under each of those.
  4. Stage new versions.
  5. Use appcmd to update the site to use the new folder.

Given an app named “Hello World” pointing to C:\Sites\HelloWorld\1.0.0  and a new build “1.0.1” that’s been staged in C:\Sites\HelloWorld\1.0.1 , when it’s time to go live, then you can use the following command to flip the site to the new version:

appcmd set vdir "Dummy Site/" /physicalPath:"c:\Sites\HelloWorld\1.0.1"

appcmd recycle apppool /apppool.name:defaultapppool

And if you need to roll back your site, run the following:

appcmd set vdir "Dummy Site/" /physicalPath:"c:\Sites\HelloWorld\1.0.0"

appcmd recycle apppool /apppool.name:defaultapppool

Here’s a great guide from Microsoft with more information on using AppCmd.

IIS reset

“iisreset” is a separate executable used to stop, start, restart IIS or event to reboot the computer (/REBOOT). You can pass it a “computername” parameter to have it control IIS on another computer. You will need to run this as admin. Many developers and system admins like to use this after a deployment, and that’s not a bad idea either!



iCACLS - Set Permissions for IIS_IUSRS group (IIS7)

icacls "D:\Website\nopcommerce\App_Data" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\bin" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Content" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Content\Images" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Content\Images\Thumbs" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Content\Images\Uploaded" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Content\files\ExportImport" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Plugins" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Plugins\bin" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\Global.asax" /grant IIS_IUSRS:(OI)(CI)F
icacls "D:\Website\nopcommerce\web.config" /grant IIS_IUSRS:(OI)(CI)F


IIS Create Application and Set Application Pool (C#)

September 12, 2018 11:48

IIS - Create Application and Set Application Pool (C#) (edit)

Chú ý:

+ Mở Visual Studio 2017 với quyền Administrator

+ Cài đặt Web Management Tools


+ Tên Root Application: MyAppPool

+ Tên Application: MyApp

+ Tên Customer: 4000


+ Tạo Application nếu chưa tồn tại.

+ Sử dụng XCopy để copy toàn bộ files từ một nguồn cho trước đến Physical Path của Application vừa tạo.

+ Hoặc Unzip từ một nguồn là 1 file .zip cho trước.

+ Set ApplicationPool trùng với ApplicationPool của Root Application.

Tham khảo

Sử dụng thư viện Microsoft.Web.Administration.dll

Sử dụng thư viện System.IO.Compression.dllSystem.IO.Compression.FileSystem.dll

1) https://forums.iis.net/t/1207235.aspx?How+to+convert+a+physical+folder+into+an+Asp+NET+Application+using+Microsoft+Web+Administration+C+API

2) https://stackoverflow.com/questions/3228813/how-to-get-websites-physical-path-on-local-iis-server-from-a-desktop-app

3) http://www.anotherchris.net/csharp/6-ways-to-get-the-current-directory-in-csharp/

4) https://dailydotnettips.com/different-ways-of-getting-path/

5) https://www.c-sharpcorner.com/UploadFile/jawedmd/xcopy-using-C-Sharp-to-copy-filesfolders/

6) https://stackoverflow.com/questions/32236796/fastest-way-to-copy-files-from-one-directory-to-another (có sử dụng dữ liệu trong Database và Sql Server Connection)





Cấu hình IIS cho ứng dụng ASP.NET

June 28, 2017 22:01

Bước 01: Vào Start / Control Panel

Bước 02: Chọn Program and Features

Bước 03: Chọn Turn Windows features on or off , Chọn IIS (Internet Information Services) và chờ trong giây lát để Windows cài đặt dịch vụ

Bước 04: Đăng ký asp.net vào hệ thống với mã lệnh “aspnet_regiis –i” với quyền Administrator

Bước 05: Mở IIS bằng cách vào Start / Control Panel / Administrative Tools / chọn dịch vụ Internet Information Services (IIS) Manager

Bước 06: Tạo Application Pools phù hợp với .NET Framework v4.0.30319

Bước 07: Tạo Application để trỏ tới website ASPNET. Lưu ý: Website đã được Publish thành tập tin .DLL

Bước 08: Chạy website từ trình duyệt với 2 cách: thông qua IIS, thông qua trình duyệt Friefox, Google Chrome, …

Chúc bạn học tập tốt.


Recent posts