New-NanoServerVHD
Creates a bootable VHD/VHDx containing Windows Server Nano 2016 RTM.
Note: As of Windows Server 2016 Technical Preview 3, the NanoServer folder in the ISO contains a new-nanoserverimage.ps1 PowerShell script that can also be used to create new Nano Server VHD/VHDx files. This script is the official one provided by Microsoft and so it should be used in any new scripts. I have updated the new-nanoservervhd.ps1 script to support TP3 so that if you have already got scripts using it then you don’t have to rewrite them to use the official one (although you probably should).
Overview
Creates a bootable VHD/VHDx containing Windows Server Nano 2016 using the publicly available Windows Server 2016 RTM ISO.
Windows Server 2016 RTM ISO can be downloaded from the Microsoft Evaluation Center here: https://www.microsoft.com/en-us/evalcenter/evaluate-windows-server-2016
This script needs the Convert-WindowsImage.ps1 script to be in the same folder.
It will be automatically downloaded from GitHub if it is not found: https://raw.githubusercontent.com/PlagueHO/New-NanoServerVHD/master/Convert-WindowsImage.ps1
This function turns the instructions on the following link into a repeatable script: https://technet.microsoft.com/en-us/library/mt126167.aspx
Please see the link for additional information.
This script can be found:
- Github Repo: https://github.com/PlagueHO/New-NanoServerVHD
- Script Center: https://gallery.technet.microsoft.com/scriptcenter/Create-a-New-Nano-Server-61f674f1
Change Log
- 2017-05-27: Updated to support new version of Convert-WindowsImage.ps1.
- 2017-05-27: Corrected readme.md markdown.
- 2016-10-14: Updated to support Windows Server 2016.
- 2016-05-14: Updated to support Windows Server 2016 TP5.
- 2015-12-01: Added WorkFolder parameter to override default work folder path.
- 2015-11-21: Offline Domain Join support added. Fix to adding SCVMM packages.
- 2015-11-20: Ability to cache base NanoServer.VHD/VHDx file to speed up creation of multiple VHD files with different packages/settings.
- 2015-11-20: Added support for Windows Server 2016 TP4.
- 2015-11-13: Added Optional Timezone Parameter. Defaults to ‘Pacific Standard Time’.
- 2015-09-18: Added support for setting IP Subnet Mask, Default Gateway and DNS Settings on first boot.
- 2015-08-20: Updated to support packages available in Windows Server 2016 TP3.
- 2015-07-24: Updated setup complete script to create a task that shows the IP Address of the Nano Server in the console window 30 seconds after boot.
- 2015-06-19: Updated to support changes in Convert-WindowsImage on 2015-06-16.
- 2015-06-19: Added VHDFormat parameter to allow VHDx files to be created.
- 2015-06-19: Added Edition parameter (defaults to CORESYSTEMSERVER_INSTALL) so that the Name of the edition in the NanoServer.WIM can be specified.
- 2015-06-19: Because of changes in Convert-WindowsImage, VHDx files are always created using the GPT partition format. VHD files are still created using MBR partition format.
- 2015-06-05: Fix to Unattend.xml to correctly set Server Name in OfflineServicing phase.
Minimum requirements
- PowerShell 4.0
License and Copyright
The MIT License (MIT)
Copyright (c) 2016 Daniel Scott-Raynsford
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the «Software»), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Example Usage
.\New-NanoServerVHD.ps1 ` -ServerISO 'D:\ISOs\Windows Server 2016\14393.0.160715-1616.RS1_RELEASE_SERVER_EVAL_X64FRE_EN-US.ISO' ` -DestVHD D:\Temp\NanoServer01.vhd ` -ComputerName NANOTEST01 ` -AdministratorPassword 'P@ssword!1' ` -Packages 'Compute','OEM-Drivers','Guest' ` -Verbose
This command will create a new VHD containing a Nano Server machine with the name NANOTEST01. It will contain only the Compute, OEM-Drivers and Guest packages. The IP Address will be configured using DHCP.
.\New-NanoServerVHD.ps1 ` -ServerISO 'D:\ISOs\Windows Server 2016\14393.0.160715-1616.RS1_RELEASE_SERVER_EVAL_X64FRE_EN-US.ISO' ` -DestVHD D:\Temp\NanoServer01.vhd ` -ComputerName NANOTEST01 ` -AdministratorPassword 'P@ssword!1' ` -Packages 'Storage','OEM-Drivers','Guest' ` -IPAddress '10.0.0.20' ` -SubnetMask '255.0.0.0' ` -GatewayAddress '10.0.0.1' ` -DNSAddresses '10.0.0.2','10,0,0,3' ` -Verbose
This command will create a new VHD containing a Nano Server machine with the name NANOTEST01. It will contain only the Storage, OEM-Drivers and Guest packages. It will set the Administrator password to P@ssword!1 and set the IP address of the first ethernet NIC to 10.0.0.20/255.0.0.0 with gateway of 10.0.0.1 and DNS set to ‘10.0.0.2’,’10,0,0,3′. It will also set the timezone to ‘Russian Standard Time’.
.\New-NanoServerVHD.ps1 ` -ServerISO 'D:\ISOs\Windows Server 2016\14393.0.160715-1616.RS1_RELEASE_SERVER_EVAL_X64FRE_EN-US.ISO' ` -DestVHD D:\Temp\NanoServer02.vhdx ` -VHDFormat VHDX ` -ComputerName NANOTEST02 ` -AdministratorPassword 'P@ssword!1' ` -Packages 'Storage','OEM-Drivers','Guest' ` -IPAddress '192.168.1.66' ` -Timezone 'Russian Standard Time' -Verbose
This command will create a new VHDx (for Generation 2 VMs) containing a Nano Server machine with the name NANOTEST02. It will contain only the Storage, OEM-Drivers and Guest packages. It will set the Administrator password to P@ssword!1 and set the IP address of the first ethernet NIC to 192.168.1.66/255.255.255.0 with no Gateway or DNS.
.\New-NanoServerVHD.ps1 ` -ServerISO 'D:\ISOs\Windows Server 2016\14393.0.160715-1616.RS1_RELEASE_SERVER_EVAL_X64FRE_EN-US.ISO' ` -DestVHD D:\Temp\NanoServer03.vhdx ` -VHDFormat VHDX ` -ComputerName NANOTEST03 ` -AdministratorPassword 'P@ssword!1' ` -Packages 'Compute','OEM-Drivers','Guest','Containers','ReverseForwarders' ` -IPAddress '192.168.1.66' ` -DJoinFile 'D:\Temp\DJOIN_NANOTEST03.TXT' ` -Verbose
This command will create a new VHDx (for Generation 2 VMs) containing a Nano Server machine with the name NANOTEST03. It will contain be configured to be a container host. It will set the Administrator password to P@ssword!1 and set the IP address of the first ethernet NIC to 192.168.1.66/255.255.255.0 with no Gateway or DNS. It will also be joined to a domain using the Offline Domain Join file D:\Temp\DJOIN_NANOTEST03.TXT.
Nano Server is a new and super small footprint of Windows Server 2016. You do not deploy by using the setup like you do with other versions of the OS. Nano Server is deployed via PowerShell. The files and scripts needed for deployment are on the Windows server 2016 ISO image. There are several different options for running Nano Server. Do you want to run as a host or on a VM? Do you want to use a custom image or a basic deployment? This article will cover these and more, giving you the information you need to get started playing with Nano Server 2016. There is no GUI and there is no RDP to a Nano Server. Remote management is however enabled by default. You simply need the IP address and credentials.
Follow the steps to get started quickly with a basic deployment of Nano Server using DHCP to obtain an IP address. The sections that come after go into more detail about further customizing the image for your specific needs, as well as remotely managing Nano Server. You can run a Nano Server VHD either in a virtual machine or boot to it on a physical computer; the steps are slightly different.
Nano Server is ideal for a number of scenarios including:
- As a “compute” host for Hyper-V virtual machines, either in clusters or not
- As a storage host for Scale-Out File Server.
- As a DNS server
- As a web server running Internet Information Services (IIS)
- As a host for applications that are developed using cloud application patterns and run in a container or virtual machine guest operating system
——————————————–
Nano Server in a virtual machine
Follow these steps to create a Nano Server VHD that will run in a virtual machine.
To quickly deploy Nano Server in a virtual machine
-
Copy NanoServerImageGenerator.psm1 and Convert-WindowsImage.ps1 from the NanoServer folder in the Windows Server Technical Preview ISO to a folder on your hard drive.
-
Start Windows PowerShell as an administrator, change directory to the folder where you’ve placed these scripts and then import the NanoServerImageGenerator script with Import-Module NanoServerImageGenerator.psm1 -Verbose
Create a VHD that sets a computer name and includes the Hyper-V guest drivers by running the following command which will prompt you for an administrator password for the new VHD:
New-NanoServerImage -MediaPath <path to root of media> -BasePath .Base -TargetPath .NanoServerVMNanoServerVM.vhd -ComputerName <computer name> -GuestDrivers where
-
<path to root of media> is the path that you provide to the root of the contents of the Technical Preview ISO. For example if you have copied the contents of the ISO to d:TP4ISO you would use that path.
-
-BasePath specifies a folder that will be created to copy the Nano Server WIM and packages to.
-
-TargetPath specifies the full path, including the filename and extension, where the resulting VHD or VHDX will be created.
-
Computer_name is the computer name you provide for the Nano Server virtual machine you are creating.
Example: New-NanoServerImage -MediaPath f: -BasePath .Base -TargetPath .Nano1Nano.vhd -ComputerName Nano1 –GuestDrivers
This example creates a VHD from an ISO mounted as f:. When creating the VHD it will use a folder called Base in the same directory where you ran New-NanoServerImage; it will place the VHD (called Nano.vhd) in a folder called Nano1 in the folder from where the command is run. The computer name will be Nano1 and will have virtual machine drivers installed for running Hyper-V.If you want a Generation 1 virtual machine, generate a VHD image by specifying a .vhd extension for -TargetPath. For a Generation 2 virtual machine, generate a VHDX image by specifying a .vhdx extension for -TargetPath.
Note
New-NanoServerImage is supported on Windows 8.1, Windows 10, Windows Server 2012 R2, and Windows Server 2016 Threshold Preview.
-
In Hyper-V Manager, create a new virtual machine and use the VHD created in Step 3.
-
Boot the virtual machine and in Hyper-V Manager connect to the virtual machine.
-
Log on to the Recovery Console (see the “Nano Server Recovery Console” section in this guide), using the administrator and password you supplied while running the script in Step 3.
-
Obtain the IP address of the Nano Server virtual machine and use Windows PowerShell remoting or other remote management tool to connect to and remotely manage the virtual machine.
——————————————–
Nano Server on a physical computer
You can also create a Nano Server VHD that will run Server Core on a physical computer, using the pre-installed device drivers. If your hardware requires a driver that is not already provided in order to boot or connect to a network, follow the steps in the “Adding Additional Drivers” section of this guide.
To quickly deploy Nano Server on a physical computer
-
Copy NanoServerImageGenerator.psm1 and Convert-WindowsImage.ps1 from the NanoServer folder in the Windows Server Technical Preview ISO to a folder on your hard drive
-
Start Windows PowerShell as an administrator, change directory to the folder where you’ve placed these scripts and then import the NanoServerImageGenerator script with Import-Module NanoServerImageGenerator.psm1 -Verbose.
-
Create a VHD that sets a computer name and includes the OEM drivers and Hyper-V by running the following command which will prompt you for an administrator password for the new VHD:
New-NanoServerImage -MediaPath <path to root of media> -BasePath .Base -TargetPath .NanoServerPhysicalNanoServer.vhd -ComputerName <computer name> -OEMDrivers -Compute where
-
<path to root of media> is the path to the root of the contents of the Technical Preview ISO. For example if you have copied the contents of the ISO to d:TP4ISO you would use that path.
-
BasePath is a folder that will be created to copy the Nano Server WIM and packages to. (This parameter is optional.)
-
TargetPath is a folder that will be created where the resulting VHD will be created.
-
Computer_name is the computer name for the Nano Server virtual machine you are creating.
Example: New-NanoServerImage -MediaPath F: -BasePath .Base -TargetPath .Nano1NanoServer.vhd -ComputerName Nano-srv1 -OEMDrivers –Compute -Clustering
This example creates a VHD from an ISO mounted as f:. When creating the VHD it will use a folder called Base in the same directory where you ran New-NanoServerImage; it will place the VHD in a folder called Nano1 in the folder from where the command is run. The computer name will be Nano-srv1 and will have OEM drivers installed for most common hardware and has the Hyper-V role and the clustering feature enabled. If the server uses UEFI to boot, change NanoServer.vhd to NanoServer.vhdx.
-
-
Log in as an administrator on the physical server where you want to run the Nano Server VHD.
-
Copy the VHD that this script creates to the physical computer and configure it to boot from this new VHD. To do that, follow these steps:
-
Mount the generated VHD. In this example, it’s mounded under D:.
-
Run bcdboot d:windows.
-
Unmount the VHD.
-
-
Boot the physical computer into the Nano Server VHD.
-
Log on to the Recovery Console (see the “Nano Server Recovery Console” section in this guide), using the administrator and password you supplied while running the script in Step 3.
-
Obtain the IP address of the Nano Server computer and use Windows PowerShell remoting or other remote management tool to connect to and remotely manage the virtual machine.
——————————————–
Custom Deployment Images
For Windows Server 2016 Technical Preview, Nano Server is distributed on the physical media, where you will find a NanoServer folder; this contains a .wim image and a subfolder called Packages. It is these package files that you use to add server roles and features to the VHD image, which you then boot to.
This table shows the roles and features that are available in this release of Nano Server, along with the Windows PowerShell options that will install the packages for them. Some packages are installed directly with their own Windows PowerShell options (such as -Compute); others you install as extensions to the -Packages option, which you can combine in a comma-separated list.
Role or feature |
Option |
||
---|---|---|---|
Hyper-V role |
-Compute |
||
Failover Clustering |
-Clustering |
||
Hyper-V guest drivers for hosting Nano Server as a virtual machine |
-GuestDrivers |
||
Basic drivers for a variety of network adapters and storage controllers. This is the same set of drivers included in a Server Core installation of Windows Server 2016 Technical Preview. |
-OEMDrivers |
||
File Server role and other storage components |
-Storage |
||
Windows Defender Antimalware, including a default signature file |
-Defender |
||
Reverse forwarders for application compatibility, for example common application frameworks such as Ruby, Node.js, etc. |
-ReverseForwarders |
||
DNS Server role |
-Packages Microsoft-NanoServer-DNS-Package |
||
Desired State Configuration (DSC) |
-Packages Microsoft-NanoServer-DSC-Package |
||
Internet Information Server (IIS) |
-Packages Microsoft-NanoServer-IIS-Package
|
||
Host support for Windows Containers |
-Containers |
||
System Center Virtual Machine Manager agent |
|
||
Network Performance Diagnostics Service (NPDS) |
-Packages Microsoft-NanoServer-NPDS-Package |
||
Data Center Bridging |
-Packages Microsoft-NanoServer-DCB-Package |
Note
When you install packages with these options, a corresponding language pack is also installed based on the configured locale of the administrator account. If, for example, your locale is set to France (fr_fr) but you are configuring a Swedish image (sv_se), you will receive an error stating that the fr_fr packages are not present. To set the cmdlet to use a different language, use the -Language parameter (for example, -Language sv_se). You can find the available language packs and their locale abbreviations in the installation media in subfolders named for the locale of the image.
Tip
To convert the WIM image to a VHD
-
Copy NanoServerImageGenerator.psm1 and Convert-WindowsImage.ps1 from the NanoServer folder in the Windows Server Technical Preview ISO to your hard drive.
-
Start an elevated Windows PowerShell console, change directory to the folder where you placed these scripts, and then import the NanoServerImageGenerator script with Import-Module NanoServerImageGenerator.psm1 -Verbose.
This example creates a GPT-based VHDX image with a given computer name and including Hyper-V guest drivers, starting with Nano Server installation media on a network share. In an elevated Windows PowerShell prompt, start with this cmdlet:
Import-Module <Server media location>NanoServerNanoServerImageGenerator.psm1; New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .FirstStepsNano.vhdx -ComputerName FirstStepsNano -GuestDrivers
The cmdlet will accomplish all of these tasks:
Prompt you for the Administrator password
Copy installation media from \PathToMediaen_us into .Base
Convert the WIM image to a VHD. (The file extension of the target path argument determines whether it creates an MBR-based VHD for Generation 1 virtual machines versus a GPT-based VHDX for Generation 2 virtual machines.)
Copy the resulting VHD into .FirstStepsNano.vhdx
Set the Administrator password for the image as specified
Set the computer name of the image to FirstStepsNano
Install the Hyper-V guest drivers
All of this results in an image of .FirstStepsNano.vhdx.
The cmdlet generates a log as it runs and will let you know where this log is located once it is finished. The WIM-to-VHD conversion accomplished by the companion script generates its own log in %TEMP%Convert-WindowsImage<GUID> (where <GUID> is a unique identifier per conversion session).
As long as you use the same base path, you can omit the media path parameter every time you run this cmdlet, since it will use cached files from the base path. If you don’t specify a base path, the cmdlet will generate a default one in the TEMP folder. If you want to use different source media, but the same base path, you should specify the media path parameter, however.
——————————————–
More tips on Nano Server
Joining Domains
New-NanoServerImage offers two methods of joining a domain; both rely on offline domain provisioning, but one harvests a blob to accomplish the join. In this example, the cmdlet harvests a domain blob for the Contoso domain from the local computer (which of course must be part of the Contoso domain), then it performs offline provisioning of the image using the blob:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .JoinDomHarvest.vhdx -ComputerName JoinDomHarvest -DomainName Contoso
When this cmdlet completes, you should find a computer named “JoinDomHarvest” in the Active Directory computer list.
You can also use this cmdlet on a computer that is not joined to a domain. To do this, harvest a blob from any computer that is joined to the domain, and then provide the blob to the cmdlet yourself. Note that when you harvest such a blob from another computer, the blob already includes that computer’s name–so if you try to add the -ComputerName parameter, an error will result.
You can harvest the blob with this command:
djoin /Provision /Domain Contoso /Machine JoiningDomainsNoHarvest /SaveFile JoiningDomainsNoHarvest.djoin
Run New-NanoServerImage using the harvested blob:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .JoinDomNoHrvest.vhd -DomainBlobPath .PathToDomainBlobJoinDomNoHrvestContoso.djoin
In the event that you already have a node in the domain with the same computer name as your future Nano Server, you could reuse the computer name by adding the -ReuseDomainNode parameter.
Injecting drivers
Nano Server offers a package that includes a set of basic drivers for a variety of network adapters and storage controllers; it’s possible that drivers for your network adapters might not be included. You can use this syntax to have New-NanoServerImage search the directory for available drivers and inject them into the Nano Server image:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .InjectingDrivers.vhdx -DriversPath .ExtraDrivers
Note
In the folder where you keep your drivers, both the SYS files and corresponding INF files must be present. Also, Nano Server only supports signed, 64-bit drivers.
Connecting with WinRM
To be able to connect to a Nano Server computer using Windows Remote Management (WinRM) (from another computer that is not on the same subnet), open port 5985 for inbound TCP traffic on the Nano Server image. Use this cmdlet:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .ConnectingOverWinRM.vhd -EnableRemoteManagementPort
Setting static IP addresses
To configure a Nano Server image to use static IP addresses, first find the name or index of the interface you want to modify by using Get-NetAdapter, netsh, or the Nano Server Recovery Console. Use the -Ipv6Address, -Ipv4Address, -Ipv4SubnetMask, or -Ipv4Gateway extensions to specify the configuration, as in this example:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .StaticIpv4.vhd -InterfaceNameOrIndex Ethernet -Ipv4Address 192.168.1.2 -Ipv4SubnetMask 255.255.255.0 -Ipv4Gateway 192.168.1.1
Custom image size
You can configure the Nano Server image to be a dynamically expanding VHD or VHDX with the -MaxSize extension, as in this example:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .BigBoss.vhd -MaxSize 100GB
Embedding custom data
To embed your own script or binaries in the Nano Server image, use the -MergePath extension:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .BigBoss.vhd -MergePath .tools
Preparing for Azure
If you want to run Nano Server in Azure, the Hyper-V guest drivers are required, along with opening the remote management port. Both of these features are provided in one step by the -ForAzure extension:
New-NanoServerImage -MediaPath \PathToMediaen_us -BasePath .Base -TargetPath .NanoServerOnAzure.vhdx -ForAzure
ToMediaen_us -BasePath .Base -TargetPath .NanoServerOnAzure.vhdx -ForAzure
Joining Nano Server to a domain
To add Nano Server to a domain online
-
Harvest a data blob from a computer in the domain that is already running Windows Threshold Server using this command:
djoin.exe /provision /domain <domain-name> /machine <machine-name> /savefile .odjblob
This saves the data blob in a file called “odjblob”.
-
Copy the “odjblob” file to the Nano Server computer with these commands:
net use z: \<ip address of Nano Server>c$
Note
If the net use command fails, you probably need to adjust Windows Firewall rules. To do this, first open an elevated command prompt, start Windows PowerShell and then connect to the Nano Server computer with Windows PowerShell Remoting with these commands:
Set-Item WSMan:localhostClientTrustedHosts “<IP address of Nano Server>”
$ip = “<ip address of Nano Server>”
Enter-PSSession -ComputerName $ip -Credential $ipAdministrator
When prompted, provide the Administrator password, then run this command to set the firewall rule:
netsh advfirewall firewall set rule group=”File and Printer Sharing” new enable=yes
Exit Windows PowerShell with Exit-PSSession, and then retry the net use command. If successful, continue copying the “odjblob” file contents to the Nano Server.
md z:Temp
copy odjblob z:Temp
-
Open an elevated command prompt, start Windows PowerShell and then connect to the Nano Server computer with Windows PowerShell remoting with these commands:
Set-Item WSMan:localhostClientTrustedHosts “<IP address of Nano Server>”
$ip = “<ip address of Nano Server>”
Enter-PSSession -ComputerName $ip -Credential $ipAdministrator
When prompted, provide the Administrator password, then run this command to join the domain:
djoin /requestodj /loadfile c:Tempodjblob /windowspath c:windows /localos
-
Restart the Nano Server computer, and then exist the Windows PowerShell session:
shutdown /r /t 5
Exit-PSSession
-
After you have joined Nano Server to a domain, add the domain user account to the Administrators group on the Nano Server.
Alternate method to join a domain in one step
First, harvest the data blob from another computer running Windows Threshold Server that is already in your domain using this command:
djoin.exe /provision /domain <domain-name> /machine <machine-name> /savefile .odjblob
Open the file “odjblob” (perhaps in Notepad), copy its contents, and then paste the contents into the <AccountData> section of the Unattend.xml file below.
Put this Unattend.xml file into the C:NanoServer folder, and then use the following commands to mount the VHD and apply the settings in the offlineServicing section:
dismdism /Mount-Image /ImageFile:.NanoServer.vhd /Index:1 /MountDir:.mountdir
dismdism /image:.mountdir /Apply-Unattend:.unattend.xml
Create a “Panther” folder (used by Windows systems for storing files during setup; see Windows 7, Windows Server 2008 R2, and Windows Vista setup log file locations if you’re curious), copy the Unattend.xml file to it, and then unmount the VHD with these commands:
md .mountdirwindowspanther
copy .unattend.xml .mountdirwindowspanther
dismdism /Unmount-Image /MountDir:.mountdir /Commit
The first time you boot Nano Server from this VHD, the other settings will be applied.
After you have joined Nano Server to a domain, add the domain user account to the Administrators group on the Nano Server.
Using the Nano Server Recovery Console
Starting with Windows Server 2016 Technical Preview, Nano Server includes an Recovery Console that ensures you can access your Nano Server even if a network mis-configuration interferes with connecting to the Nano Server. You can use the Recovery Console to fix the network and then use your usual remote management tools.
When you boot Nano Server in either a virtual machine or on a physical computer that has a monitor and keyboard attached, you’ll see a full-screen, text-mode logon prompt. Log into this prompt with an administrator account to see the computer name and IP address of the Nano Server. You can use these commands to navigate in this console:
-
Use arrow keys to scroll
-
Use TAB to move to any text that starts with >; then press ENTER to select.
-
To go back one screen or page, press ESC. If you’re on the home page, pressing ESC will log you off.
-
Some screens have additional capabilities displayed on the last line of the screen. For example, if you explore a network adapter, F4 will disable the network adapter.
In Windows Server 2016 Technical Preview, the Recovery Console allows you to view and configure network adapters and TCP/IP settings, as well as firewall rules.
Managing Nano Server remotely
Nano Server is 100% managed remotely. There is no local logon capability at all, nor does it support Terminal Services. However, you have a wide variety of options for managing Nano Server remotely, including Windows PowerShell, Windows Management Instrumentation (WMI), Windows Remote Management, and Emergency Management Services (EMS).
To use any remote management tool, you will probably need to know the IP address of the Nano Server. Some ways to find out the IP address include:
-
Use the Nano Recovery Console (see the Using the Nano Server Recovery Console section of this topic for details).
-
Connect a serial cable to the computer and use EMS.
-
Using the computer name you assigned to the Nano Server while configuring it, you can get the IP address with ping. For example, ping NanoServer-PC /4.
Using Windows PowerShell remoting
To manage Nano Server with Windows PowerShell remoting, you need to add the IP address of the Nano Server to your management computer’s list of trusted hosts, add the account you are using to the Nano Server’s administrators, and enable CredSSP if you plan to use that feature.
To add the Nano Server to the list of trusted hosts, run this command at an elevated Windows PowerShell prompt:
Set-Item WSMan:localhostClientTrustedHosts “<IP address of Nano Server>”
To start the remote Windows PowerShell session, start an elevated local Windows PowerShell session, and then run these commands:
$ip = “<IP address of Nano Server>”
$user = “$ipAdministrator”
Enter-PSSession -ComputerName $ip -Credential $user
You can now run Windows PowerShell commands on the Nano Server as normal.
Note
Not all Windows PowerShell commands are available in this release of Nano Server. To see which are available, run Get-Command -CommandType Cmdlet
Stop the remote session with the command Exit-PSSession
Using Windows PowerShell CIM sessions over WinRM
You can use CIM sessions and instances in Windows PowerShell to run WMI commands over Windows Remote Management (WinRM).
Start the CIM session by running these commands in a Windows PowerShell prompt:
$ip = “<IP address of the Nano Server>”
$ipAdministrator
$cim = New-CimSession –Credential $user –ComputerName $ip
With the session established, you can run various WMI commands, for example:
Get-CimInstance –CimSession $cim –ClassName Win32_ComputerSystem | Format-List *
Get-CimInstance -CimSession $Cim -Query “SELECT * from Win32_Process WHERE name LIKE ‘p%’”
Windows Remote Management
You can run programs remotely on the Nano Server with Windows Remote Management (WinRM). To use WinRM, first configure the service and set the code page with these commands at an elevated command prompt:
winrm quickconfig
winrm set winrm/config/client @{TrustedHosts=”*”}
chcp 65001
Now you can run commands remotely on the Nano Server. For example:
winrs –r:<IP address of Nano Server> -u:Administrator -p:<Nano Server administrator password> ipconfig
For more information about Windows Remote Management, see <LINKS>.
Using Hyper-V on Nano Server
Hyper-V works the same on Nano Server as it does on Windows Server in Server Core mode, with two exceptions:
-
You must perform all management remotely and the management computer must be running the same build of Windows Server as the Nano Server. Older versions of Hyper-V Manager or Hyper-V Windows PowerShell cmdlets will not work.
-
RemoteFX is not available.
In this release, these features of Hyper-V have been verified:
-
Enabling Hyper-V
-
Creation of Generation 1 and Generation 2 virtual machines
-
Creation of virtual switches
-
Starting virtual machines and running Windows guest operating systems
Note
Hyper-V Replica is not supported in this release.
If you want to perform a live migration of virtual machines, create a virtual machine on an SMB share, or connect resources on an existing SMB share to an existing virtual machine, it is vital that you configure authentication correctly. You have two options for doing this:
Constrained delegation
Constrained delegation works exactly the same as in previous releases. Refer to these articles for more information:
-
Enabling Hyper-V Remote Management – Configuring Constrained Delegation For SMB and Highly Available SMB
-
Enabling Hyper-V Remote Management – Configuring Constrained Delegation For Non-Clustered Live Migration
CredSSP
First, refer to the “Using Windows PowerShell remoting” section of this topic to enable and test CredSSP. Then, on the management computer, you can use Hyper-V Manager and select the option to “connect as another user.” Hyper-V Manager will use CredSSP. You should do this even if you are using your current account.
Windows PowerShell cmdlets for Hyper-V can use CimSession or Credential parameters, either of which work with CredSSP.
Using Failover Clustering on Nano Server
Failover clustering works the same on Nano Server as it does on Windows Server in Server Core mode, but keep these caveats in mind:
-
Clusters must be managed remotely with Failover Cluster Manager or Windows PowerShell.
-
All Nano Server cluster nodes must be joined to the same domain, similar to cluster nodes in Windows Server.
-
The domain account must have Administrator privileges on all Nano Server nodes, as with cluster nodes in Windows Server.
-
All commands must be run in an elevated command prompt.
Note
Additionally, certain features are not supported in this release:
-
You cannot run failover clustering cmdlets on a local Nano Server through Windows PowerShell.
-
Clustering roles other than Hyper-V and File Server.
You’ll find these Windows PowerShell cmdlets useful in managing Failover clusters:
You can create a new cluster with New-Cluster -Name <clustername> -Node <comma-separated cluster node list>
Once you’ve established a new cluster, you should run Set-StorageSetting -NewDiskPolicy OfflineShared on all nodes.
Add an additional node to the cluster with Add-ClusterNode -Name <comma-separated cluster node list> -Cluster <clustername>
Remove a node from the cluster with Remove-ClusterNode -Name <comma-separated cluster node list> -Cluster <clustername>
Create a Scale-Out File Server with Add-ClusterScaleoutFileServerRole -name <sofsname> -cluster <clustername>
You can find additional cmdlets for failover clustering at Microsoft.FailoverClusters.PowerShell.
Using DNS Server on Nano Server
To provide Nano Server with the DNS Server role, add the Microsoft-NanoServer-DNS-Package to the image (see the “Creating a custom Nano Server image” section of this topic. Once the Nano Server is running, connect to it and run this command from and elevated Windows PowerShell console to enable the feature:
Enable-WindowsOptionalFeature -Online -FeatureName DNS-Server-Full-Role
Using IIS on Nano Server
For steps to use the Internet Information Services (IIS) role, see IIS on Nano Server.
Source: Getting Started with Nano Server Please see the post for even more great information https://technet.microsoft.com/en-us/library/mt126167.aspx
Last week Microsoft released Windows Server 2016 with the first GA release of Nano Server. A couple of months back I already wrote a blog post how you can create a new Nano Server Image in Technical Preview 4. This post is an updated version of that this post using Windows Server 2016 GA. In this post I will quickly show you how you can create a new VHD, VHDX or WIM file with your Nano Server configuration.
This is the PowerShell option, you can also use the Nano Server Image Builder.
First you have to download the latest Windows Server 2016 ISO file.
If you open the Windows Server 2016 ISO file you can see a folder called “NanoServer” on the medium. This folder includes:
- NanoServer.wim – This is the Nano Server Image file
- Packages – The Package folder includes the Nano Server Packages, Windows Roles and Features and some basic drivers
- NanoServerImageGenerator – In this folder you can find the Nano Server Image Generator PowerShell Module
I usually create a folder on my C:\NanoServer to store all the things I need, which makes things a little simpler.
- Base – This is a temporary folder where the images get mounted while updating or creating new images
- Drivers – This is the folder where I copy all the drivers for a physical image
- Files – This is the unpacked Windows Server 2016 ISO image (including, the sources folder, NanoServer folder, support, boot and efi folder as well as the setup.exe file)
- Images – In this folder I store all the new created images
- Updates – In this folder I store the Windows Server 2016 Update cumulative updates (.cab files)
- XMLs – In this folder I store unattend.xml files if I need to do a extended configuration.
Of course you don’t have to use this folder structure, but it makes things easier.
If you have a look at the Packages folder you can find all the available packages for Nano Server:
A new Nano Server Image can be created using the New-NanoServerImage PowerShell cmdlet. This will create a new Nano Server Image in a VHDX including the VM Guest drivers and nothing more.
# Change Working Directory cd C:\NanoServer # Import Module Import-Module .\NanoServerImageGenerator.psm1 # Create Nano Server Image VHDX New-NanoServerImage -MediaPath .\Files -BasePath .\Base -TargetPath .\Images\NanoVMGA.vhdx -MaxSize 20GB -DeploymentType Guest -Edition Datacenter -ComputerName "Nano01"
- MediaPath – The location with the Windows Server 2016 files
- BasePath – Temporary folder to mount the WIM file
- TargetPath – Where the new Image file gets stored. You can create a .wim, .vhd or .vhdx file
- .vhd creates a Image for a Generation 1 VM (BIOS boot)
- .vhdx create a Image for a Generation 2 VM (UEFI boot)
- DeploymentType allows you to choose between Guest and Host
- Guest creates a Virtual Machine
- Host creates a Physical Image
- Edition can be Standard or Datacenter
- ComputerName adds the server name of the Nano Server
- MaxSize changes the Partition size, if you are not using this parameter it will create a default partition of 4GB
You can now copy the VHDX file from the Images folder, attach this to a new Hyper-V virtual machine and boot.
This will show the Nano Server recovery console:
There are more parameters to add roles and features, updates, drivers and additional configuration like IP addresses and more
For example if you want to add some updates to the Nano Server Image you can use the following cmdlet:
# Create Nano Server Image VHD with updates New-NanoServerImage -MediaPath .\Files -BasePath .\Base -TargetPath .\Images\NanoVM.vhd -MaxSize 20GB -DeploymentType Guest -Edition Datacenter -ComputerName "Nano01" -ServicingPackagePath ".\Updates\Windows10.0-KB3176936-x64.cab", ".\Updates\Windows10.0-KB3176936-x64.cab"
To add a fixed IP address you can for example use the following cmdlet:
# Create Nano Server with IP address New-NanoServerImage -MediaPath .\Files -BasePath .\Base -TargetPath .\Images\NanoVMSetupUI.vhdx -MaxSize 20GB -DeploymentType Guest -Edition Datacenter -ComputerName "Nano01" -Ipv4Address "172.21.22.101" -Ipv4SubnetMask "255.255.255.0" -Ipv4Gateway "172.21.22.1" -Ipv4Dns "8.8.8.8"
If you have some advanced deployment you can use for example the following thing, which helps you to set different configuration options. This example here is designed for a physical Hyper-V host
# Nano Server Packages for Image $NanoPackages = "Microsoft-NanoServer-Compute-Package", "Microsoft-NanoServer-DCB-Package", "Microsoft-NanoServer-DSC-Package", "Microsoft-NanoServer-FailoverCluster-Package", "Microsoft-NanoServer-OEM-Drivers-Package", "Microsoft-NanoServer-Storage-Package" $ServicingPackagePath = ".\Updates\Windows10.0-KB3176936-x64.cab", ".\Updates\Windows10.0-KB3176936-x64.cab" $UnattanedXML = ".\XMLs\unattend.xml" $MaxSize = 20GB $Edition = "Datacenter" $VHDXName = ".\Images\NanoHost01.vhdx" $DeploymentType = "Host" $DriverPath = ".\Drivers" $MediaPath = ".\Files" $BasePath = ".\Base" $ComputerName = "Nano01" $DomainName = "thomasmaurer.ch" #IP Configuration if not DHCP #$Ipv4Address = "172.21.22.101" #$Ipv4SubnetMask = "255.255.255.0" #$Ipv4Gateway = "172.21.22.1" #$Ipv4Dns = "8.8.8.8" # Nano Image New-NanoServerImage -MediaPath $MediaPath -BasePath $BasePath -TargetPath $VHDXName -DriversPath $DriverPath -DeploymentType $DeploymentType -Edition $Edition -Packages $NanoPackages -MaxSize $MaxSize -ServicingPackagePath $ServicingPackagePath -UnattendPath $UnattanedXML -ComputerName $ComputerName -DomainName $DomainName
You can for example use this VHDX file now to create a boot from VHDX scenario:
# Boot from VHDX Mount-VHD C:\VHDX\NanoHost01.vhdx -Passthru | get-disk | Get-Partition | where Size -GE 3GB | Set-Partition -NewDriveLetter V # Set Boot Partition cd v:\windows\system32 bcdboot v:\windows # Unmounted Get-VHD C:\VHDX\NanoHost01.vhdx | Dismount-VHD
I hope this helps you to get started with Nano Server in Windows Server 2016. I also prepared a blog post how you can create a Nano Server Image using the Nano Server Image Builder tool.
Tags: Create Image, Hyper-V, Image, Microsoft, Nano Server, PowerShell, Server, VHD, VHDX, Windows Server, Windows Server 2016 Last modified: June 26, 2019
About the Author / Thomas Maurer
Thomas works as a Principal Program Manager & Chief Evangelist Azure Hybrid at Microsoft (Cloud + AI). He engages with the community and customers around the world to share his knowledge and collect feedback to improve the Azure hybrid cloud and edge platform. Prior to joining the Azure engineering team (Cloud + AI), Thomas was a Lead Architect and Microsoft MVP, to help architect, implement and promote Microsoft cloud technology.
If you want to know more about Thomas, check out his blog: www.thomasmaurer.ch and Twitter: www.twitter.com/thomasmaurer
Recently I have been doing some research on Windows Server 2016 Technical Preview 3 Nano Server on VMware ESXi Hypervisor and I can hardly find any online article that demonstrate it. After much experimenting with a few builds, I have decided to share this knowledge out on Microsoft TechNet Wiki.
You can either view this article from the Microsoft TechNet Wiki which may have any improvement updates by the TechNet community on the link below;
- http://social.technet.microsoft.com/wiki/contents/articles/32731.vmware-windows-nano-server-how-to-build-them.aspx
Or carry on reading this page on the original article which I have noted in my engineering journal with some explanations on the process.
The Original TechNet Wiki Article on VMware + Windows Nano Server = How to build them?
Introduction
Have you heard of the new awesome Microsoft Windows Nano Server? I discovered that most of the built articles are revolving on physical hardware, Hyper-V and not forget, Azure. If your hypervisor environment is using VMware vSphere, those may just slightly miss the bandwagon to test Nano Server in their environment. Well, this article is going to change the game play a bit because I want to test it out on vSphere 6.0 and cannot just let the Hyper-V hypervisor have all the fun.
Other Hypervisor Articles;
- OpenStack + Windows Nano Server
So this article will be VMware + Windows Nano Server. Let us begin the journey.
Preparation for Nano Server Image
At the time of creating this article, we will be focusing on Windows Server 2016 Technical Preview 3.
Where is the NanoServer content?
The NanoServer folder reside in the Windows Server 2016 Technical Preview DVD Media.
Where do I start?
Copy the NanoServer folder from the media to the local drive using PowerShell.
# Find out the CD-ROM Drive Letter Get-Volume | ` ?{$_.DriveType -eq "CD-ROM"} ;
# Copy the NanoServer folder from the Windows Server 2016 # Technical Preview 3 DVD media Copy-Item ` -Path Z:\NanoServer ` -Destination C:\ ` -Recurse ` -Verbose ;
Preparation for VMware Tools Drivers
This section focuses on extracting VMware Tools in preparation to slipstream the mandatory drivers. If you are struggling with this, you may want to collaborate with your VMware evangelist and work together.
Where is the VMware Tools for Windows media located?
SSH to VMware vSphere ESXi 6.0 Host using PuTTY.
ls -l vmimages/tools-isoimages/win*
Download the vmimages/tools-isoimages/windows.iso file using WinSCP to the machine for content extraction
If your machine is also a VMware virtual machine, you can manually mount the ISO by following the article below;
- Installing VMware Tools manually from the ISO image (1003910) – http://kb.vmware.com/kb/1003910
How do I extract VMware Tools content from the ISO media file?
This is how to extract the VMware Tools content using the ISO Media with VMware Tools Installation Wizard to the destination folder below using PowerShell.
# Create a VMware_Tools_Extracted folder for extracting # VMware Tools installation content New-Item ` -Path C:\NanoServer\VMware_Tools_Extracted ` -Type directory ;
# Mount the Windows VMware Tools ISO Mount-DiskImage ` -ImagePath C:\windows.iso ;
# Find the mounted Windows VMware Tools ISO Drive Letter (Get-DiskImage -ImagePath C:\windows.iso | Get-Volume).DriveLetter
# Execute VMware Tools Setup64.exe and extract the content to # C:\NanoServer\VMware_Tools_Extracted folder using the # Installation Wizard <# Mounted Windows VMware Tools Drive Letter #>:\setup64.exe /a /p C:\NanoServer\VMware_Tools_Extracted # Eg. d:\setup64.exe /a /p C:\NanoServer\VMware_Tools_Extracted
Unfortunately, the VMware Tools command will prompt the VMware Tools Installation Wizard graphical user interface and therefore it cannot be scripted. User intervention on the graphical user interface is required to complete the extraction to the destination folder as shown on the screenshots below;
- Select Next
- Select Destination Folder
- Select Finish
Once the VMware Tools Installation Wizard has completed the extraction to the destination folder, remember to dismount the VMware Tools ISO media using the PowerShell.
# Dismount the Windows VMware Tools ISO Dismount-DiskImage ` -ImagePath C:\windows.iso ;
How do I extract VMware Tools content from manually mounted ISO image?
Create a folder to contain the extracted VMware Tools content using PowerShell.
# Create a VMware_Tools_Extracted folder for extracting # VMware Tools installation content New-Item ` -Path C:\NanoServer\VMware_Tools_Extracted ` -Type directory ;
If your machine is also a VMware virtual machine and you have already mounted the VMware Tools ISO image, you can extract the VMware Tools content by following the article below;
- Extracting the drivers from VMware Tools bundled with VMware Workstation (2032184) – http://kb.vmware.com/kb/2032184
Extract the content into the destination folder using the VMware Tools Installation Wizard graphical user interface and unmount the ISO image.
What VMware Tools drivers should I include in NanoServer?
Before we prepare the VMware Tools drivers to be included in NanoServer, I like to be a bit tidy in containing what I need in a separate folder so that I don’t get confuse. Create a VMware Drivers folder within the parent NanoServer folder using PowerShell.
# Create a VMware Drivers folder New-Item ` -Path C:\NanoServer\VMware-Drivers ` -ItemType directory ;
Selecting the VMware drivers required for NanoServer as a guest virtual machine is very important. In order to understand what are those from the documentation link below;
- VMware Tools Device Drivers – https://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.vsphere.vm_admin.doc/GUID-6994A5F9-B62B-4BF1-99D8-E325874A4C7A.html
# Copy VMware Tools Memory Control Driver - This driver is Mandatory Copy-Item ` -Path 'C:\NanoServer\VMware_Tools_Extracted\VMware\VMware Tools\VMware\Drivers\memctl\*' ` -Destination C:\NanoServer\VMware-Drivers ` -Recurse ` -Verbose ; # Copy VMware Tools Paravirtual SCSI (PVSCSI) Drivers - Optional Copy-Item ` -Path 'C:\NanoServer\VMware_Tools_Extracted\VMware\VMware Tools\VMware\Drivers\pvscsi\*' ` -Destination C:\NanoServer\VMware-Drivers ` -Recurse ` -Verbose ; # Copy VMware Tools SVGA 3D Video (SVGA) Drivers - Optional Copy-Item ` -Path 'C:\NanoServer\VMware_Tools_Extracted\VMware\VMware Tools\VMware\Drivers\video_wddm\*' ` -Destination C:\NanoServer\VMware-Drivers ` -Recurse ` -Verbose ; # Copy VMware Tools Virtual Machine Communication Interface (VMCI) # Drivers - Optional Copy-Item ` -Path 'C:\NanoServer\VMware_Tools_Extracted\VMware\VMware Tools\VMware\Drivers\vmci\device\*' ` -Destination C:\NanoServer\VMware-Drivers ` -Recurse ` -Verbose ; # Copy VMware Tools VMXNet NIC (VMXNET3) Drivers - This # driver is Mandatory for using VMXNET3 Network Interface. Copy-Item ` -Path 'C:\NanoServer\VMware_Tools_Extracted\VMware\VMware Tools\VMware\Drivers\vmxnet3\NDIS6\*' ` -Destination C:\NanoServer\VMware-Drivers ` -Recurse ` -Verbose ;
Getting Started with Nano Server Creation
With Windows Server 2016 Technical Preview 3, Microsoft has simplified the Nano Server creation with 2 PowerShell scripts that we have copied across to the local drive during the preparation for Nano Server image and we will use them in the example below.
Firstly, we need to ensure that we are at the working folder where the New-NanoServerImage PowerShell script is located. The reason is that if you are not in that working folder, you may encounter errors when the script is going to invoke the Convert-WindowsImage PowerShell script written by Pronichkin.
# Ensure you are at C:\NanoServer working folder Set-Location ` -Path C:\NanoServer ;
Secondly, we will have to import the New-NanoServerImage PowerShell script module using PowerShell.
# Import New-NanoServerImage PowerShell Module Import-Module ` -Global C:\NanoServer\new-nanoserverimage.ps1 ;
Next, we will create a basic NanoServer image with no role or feature except for the basic necessities. For a more detail documentation of how to create a NanoServer, you can read up more from the link below;
- Getting Started with Nano Server documentation – https://technet.microsoft.com/en-us/library/mt126167.aspx.
We need to ensure that -GuestDrivers parameter is included to allow you to have keyboard functionality when you launch the remote console using VMware vSphere 6.0 Web Client.
Remember the VMware Tools drivers that we have extracted and copied to another destination folder just now? We will need to include the -DriversPath parameter and specify the copied VMware drivers folder path.
Using the PowerShell command, we will concatenate those parameters into a single command to initiate the creation of a new basic Nano Server.
# Create New Basic NanoServer Image New-NanoServerImage ` -MediaPath Z: ` -BasePath C:\NanoServer\Base ` -TargetPath C:\NanoServer\NanoServer ` -ComputerName NanoServer ` -EnableRemoteManagementPort ` -Language 'en-us' ` -GuestDrivers ` -DriversPath C:\NanoServer\VMware-Drivers ` -AdministratorPassword (ConvertTo-SecureString -String "Password" -AsPlainText -Force) ;
Done. We have a Nano Server created on a Generation 1 VHD virtual disk that can be mounted and boot up on a Hyper-V host. If you have included the VMware Paravirtual SCSI (PVSCSI) Drivers, you definitely can boot it up on your VMware vSphere ESXi 6.0 host provided that your virtual machine is using PVSCSI controller for the VMDK disk. But… Firstly, we generally prefer LSI SAS controller for Windows. Secondly, how do you get it running in vSphere?
Injecting LSI SAS storage driver into Nano Server
First of all, we need to find the LSI SAS storage controller driver folder path within a Windows Operating System since it is a Microsoft driver.
# Find lsi_sas.sys Storage Driver Get-ChildItem ` -Path C:\Windows\System32\DriverStore ` -Filter lsi_sas.sys ` -Recurse ;
Next, we need to create an empty moundir folder for DISM to mount the VHD.
# Create a MountDir folder for Deployment Image Servicing and Management (DISM) New-Item ` -Path C:\NanoServer\mountdir ` -ItemType directory ;
Next, we use DISM to mount the NanoServer VHD into the mountdir folder.
# Mount NanoServer.vhd vDisk on C:\MountDir folder dism /mount-image /imagefile:c:\nanoserver\nanoserver\nanoserver.vhd /index:1 /mountdir:c:\nanoserver\mountdir
Once we done that, we can inject the LSI SAS storage controller driver by specifying the folder path.
# Add the lsi_sas.sys storage controller driver into C:\MountDir folder dism /add-driver /image:c:\nanoserver\mountdir /driver:C:\Windows\System32\DriverStore\FileRepository\lsi_sas.inf_amd64_2bd0ac9c0d7785b0
After that, we dismount the mountdir folder.
# Unmount NanoServer.vhd vDisk from C:\MountDir folder dism /unmount-image /mountdir:c:\nanoserver\mountdir /commit
Once this is performed, the Nano Server will be able to boot up on LSI SAS storage controller with VMDK disk attached. We can also safely regard this NanoServer.vhd is the new base image for your VMware environment although I haven’t shown you how to get it into the vSphere 6.0 yet.
Adding role or feature over the existing Nano Server VHD
Alright, a Nano Server without any role or feature will not be of any use to anyone. Since we currently have a proper NanoServer.vhd base image, we can use the new base image to recreate another Nano Server VHD with roles or feature.
Let’s find out the full path of our base image that we created just now.
# Verify the existing NanoServer VHD Path Get-ChildItem ` -Path C:\NanoServer\NanoServer\ | ` Select ` FullName, ` Length ;
In this process of adding a Hyper-V role, we included the -Compute parameter on the PowerShell command. This will instruct it to include the Microsoft-NanoServer-Compute-Package.cab file during repackaging. We also need to include the -ExistingVHDPath parameter and specify our existing base image full path.
For a full reference of the available Nano Server role and feature included in Windows Server 2016 Technical Preview 3, you can find them in the link of the documentation below;
- Getting Started with Nano Server – https://technet.microsoft.com/en-us/library/mt126167.aspx
# Create a New NanoServer with Hyper-V role # using existing NanoServer Base Image New-NanoServerImage ` -MediaPath Z: ` -BasePath C:\NanoServer\Base ` -TargetPath C:\NanoServer\NanoServer-Compute ` -ExistingVHDPath C:\NanoServer\NanoServer\NanoServer.vhd ` -ComputerName NanoServer ` -Compute ` -EnableRemoteManagementPort ` -Language 'en-us' ` -GuestDrivers ` -AdministratorPassword (ConvertTo-SecureString -String "Password" -AsPlainText -Force) ;
Once this is completed, you will notice that the new NanoServer-Compute.vhd has a different file length size now. It is slightly bigger than the base image.
# Verify the new NanoServer with Hyper-V role VHD Path Get-ChildItem ` -Path C:\NanoServer\NanoServer-Compute\ | ` Select ` FullName, ` Length ;
Getting Started with Nano Server Disk Footprint
Since we have found out that adding a role or feature increases the NanoServer-Compute.vhd file size, we need to find out the actual size of our VHD because it represent the hard disk size of the Nano Server operating system volume.
# Get the NanoServer-Compute.vhd current default disk size information Get-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhd | ` Select ` @{L='Path';E={$_.Path}}, ` VhdFormat, ` VhdType, ` @{L='FileSize in Byte';E={$_.FileSize}},` @{L='FileSize in KB';E={$_.FileSize/1KB}}, ` @{L='FileSize in MB';E={$_.FileSize/1MB}}, ` @{L='FileSize in GB';E={$_.FileSize/1GB}}, ` @{L='Size in Byte';E={$_.Size}}, ` @{L='Size in GB';E={$_.Size/1GB}}, ` @{L='MinimumSize in Byte';E={$_.MinimumSize}}, ` @{L='MinimumSize in GB';E={$_.MinimumSize/1GB}}, ` FragmentationPercentage ;
By default using New-NanoServerImage command in Windows Server 2016 Technical Preview 3, the Nano Server will be created with Generation 1 VHD in Dynamic VHD Type with 40GB disk partition containing about ~461MB of files. For VMware enthusiasts, it means 40GB Thin Provisioned Disk with about ~461MB consumed space for files.
How to reduce Nano Server 40GB VHD to 4GB VHD?
True, Nano Server is indeed very small and it can be less than 1GB depending on how many drivers, roles or features has been included in the built. But do we really need 40GB Dynamic VHD? I do not have an answer for it. But the process below demonstrates on how to reduce the disk from 40GB to less than 4GB to fit into a 4GB VMDK.
Firstly, we need to convert the Nano Server Generation 1 VHD to a Generation 2 VHD.
# Convert the NanoServer-Compute.vhd Generation 1 VHD to # NanoServer-Compute.vhdx Generation 2 VHDX format Convert-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhd ` -DestinationPath C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhdx ` -VHDType Dynamic ` -DeleteSource ;
Prior to resizing, we will get the current disk information of the VHDX to prove that the resizing has performed according to plan.
# Get the new NanoServer-Compute.vhdx current default disk size # information Get-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhdx | ` Select ` @{L='Path';E={$_.Path}}, ` VhdFormat, ` VhdType, ` @{L='FileSize in Byte';E={$_.FileSize}},` @{L='FileSize in KB';E={$_.FileSize/1KB}}, ` @{L='FileSize in MB';E={$_.FileSize/1MB}}, ` @{L='FileSize in GB';E={$_.FileSize/1GB}}, ` @{L='Size in Byte';E={$_.Size}}, ` @{L='Size in GB';E={$_.Size/1GB}}, ` @{L='MinimumSize in Byte';E={$_.MinimumSize}}, ` @{L='MinimumSize in GB';E={$_.MinimumSize/1GB}}, ` FragmentationPercentage ;
Next, we mount the VHDX locally and get the virtual disk internal volume information to verify the volume structure is correct as stated before any manipulation made.
# Mount the NanoServer-Compute.vhdx and get the NanoServer # system drive partition volume size Mount-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhdx ` -Passthru | ` Get-Disk | ` Get-Partition | ` Get-Volume ;
By default, the New-NanoServerImage.ps1 PowerShell Module utilise the Convert-WindowsImage.ps1 PowerShell Module to create the VHD vDisk with the default size value of 40GB and the default size of 40GB may not fit into a USB Flash Thumb Drive if your solution implementation required although it is a Dynamic VHD Type.
With the VHD being mounted, we can start resizing the VHD virtual disk internal partition.
# Resize the Partition inside Generation 2 VHD Resize-Partition ` -DriveLetter D ` -Size (((4GB - ((512KB * 2) + (512KB * 2))) - 300MB ) - 600MB) ;
Well, it is arguable that the Disk Size in GB is going to be far less than 4GB and that is because;
- We reduced 1024KB for VHD Header and 1024KB VHD Footer to align the space to fit into 4GB VMDK
- We reduced 300MB for System Reserved partition for Boot Manager code and Boot Configuration Database
- We reduced 600MB from the Partition and VHD to provide free working space on the VMDK for the expansion of the attached VHD vDisk during boot up.
Next, we dismount the VHD vDisk from the local machine to resize the VHD.
# Dismount the NanoServer-Compute.vhdx Generation 2 VHD Dismount-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhdx ;
Once the VHD has been dismounted, the VHD file will not be locked and we can start resizing the VHD.
# Resize the NanoServer-Compute.vhdx Generation 2 VHD Resize-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhdx ` -ToMinimumSize ;
After the VHD has been resized, we can start converting the Generation 2 VHD back to Generation 1 VHD to keep consistent file type with the script output.
# Convert the NanoServer-Compute.vhdx Generation 2 VHD back # to NanoServer-Compute.vhd Generation 1 VHD format Convert-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhdx ` -DestinationPath C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhd ` -VHDType Dynamic ` -DeleteSource ;
Now the moment of truth, we will obtain the VHD information and verify it has been reduced in size.
# Get the new NanoServer.vhd current default disk size information Get-VHD ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhd | ` Select ` @{L='Path';E={$_.Path}}, ` VhdFormat, ` VhdType, ` @{L='FileSize in Byte';E={$_.FileSize}},` @{L='FileSize in KB';E={$_.FileSize/1KB}}, ` @{L='FileSize in MB';E={$_.FileSize/1MB}}, ` @{L='FileSize in GB';E={$_.FileSize/1GB}}, ` @{L='Size in Byte';E={$_.Size}}, ` @{L='Size in GB';E={$_.Size/1GB}}, ` @{L='MinimumSize in Byte';E={$_.MinimumSize}}, ` @{L='MinimumSize in GB';E={$_.MinimumSize/1GB}}, ` FragmentationPercentage ;
Now we have Nano Server with Hyper-V role that is less than 4GB in VHD which can fit into a 4GB VMDK, but it is still in a VHD format for Hyper-V Host and we need to get it hosted within a vSphere ESXi host.
Getting Started with Nano Server deployment in vSphere ESXi
Before we start, we will have to ensure that have created a Virtual Machine on vSphere ESXi host with the correct virtual hardware specification where the Nano Server image will boot up from. We will also requires a Windows Preinstallation Environment (WinPE) to boot up and perform some system preparation configuration on the Virtual Machine.
What is the requirement?
We will need to download and install the Windows Assessment and Deployment Kit (ADK) for Windows 10 and install the Windows Preinstallation Environment (Windows PE) feature to allows us to create a Windows PE image.
To obtain Windows Assessment and Deployment Kit (ADK) for Windows 10, you can download it from the link below; http://go.microsoft.com/fwlink/p/?LinkId=526740
Preparing Nano Server VHD using Windows PE for vSphere ESXi
With all the preparation of the Nano Server VHD completed, we will need to prepare a media to boot into Windows Preinstallation Environment with our Nano Server VHD file. This is because we cannot mount the VHD file type into the Guest Virtual Machine on ESXI using vSphere 6.0 Web Client.
Let’s jump into the Windows Assessment and Deployment environment now.
# Enter into the Windows Assessment and Deployment # Kit (ADK) environment from PowerShell console C:\Windows\system32\cmd.exe /k "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\DandISetEnv.bat"
Use the command script provided in that environment to copy the Windows PE media content.
# Copy the Windows Preinstallation Environment (WinPE) # media content for amd64 into your working folder "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\copype.cmd" amd64 "C:\NanoServer\WindowsPE AMD64 - Windows Server 2016 TP3 - Nano Server"
Let’s exit the ADK environment into PowerShell environment.
# Return back to PowerShell Console PowerShell
We will have to manually create an empty VHD folder within the Windows PE media folder to keep our Nano Server VHD file.
# Create a VHD folder in Windows PE Media Folder New-Item ` -Path "C:\NanoServer\WindowsPE AMD64 - Windows Server 2016 TP3 - Nano Server\media\VHD" ` -Type directory ;
Copy the Nano Server VHD file to that newly create VHD folder in the Windows PE media folder. It has to be in the media folder so that the file will be included when we compile it into an ISO image.
# Copy NanoServer-Compute.vhd vDisk to Windows PE # Media VHD Folder Copy-Item ` -Path C:\NanoServer\NanoServer-Compute\NanoServer-Compute.vhd ` -Destination "C:\NanoServer\WindowsPE AMD64 - Windows Server 2016 TP3 - Nano Server\media\VHD" ` -Recurse ` -Verbose ;
Let’s return back to the ADK environment to use another command script for compiling to ISO image.
# Return back into the Windows Assessment and Deployment # Kit (ADK) environment from PowerShell console C:\Windows\system32\cmd.exe /k "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\DandISetEnv.bat"
Using the command script, we begin the compilation by specifying the Windows PE folder and the ISO Image file destination path.
# Create the Windows PE ISO from the Windows PE Media folder "C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Windows Preinstallation Environment\MakeWinPEMedia.cmd" /ISO "C:\NanoServer\WindowsPE AMD64 - Windows Server 2016 TP3 - Nano Server" "C:\NanoServer\NanoServer-Compute\Windows_Server_2016_TP3_-_Nano_Server_for_vSphere_6.0.ISO"
Once you obtained the ISO image file, you will need to mount the ISO image file on the Guest Virtual Machine using vSphere 6.0 Web Client and Power On the Guest VM.
Partitioning the VMDK using DiskPart in Windows PE
Powering On the Guest for the first time with Windows PE, we will automatically boot into Windows PE with a Command Prompt and it will be the interface that we will be using to partition the VMDK.
Firstly, we will use DiskPart to clean the VMDK Disk to ensure that the disk has no volume or partition structure.
:: Clean the Disk 0 diskpart select disk 0 clean
If you prefer to do this using PowerShell instead of DiskPart within Windows Preinstallation Environment (Windows PE), you will have to follow this guide on how to add PowerShell support into Windows PE prior creating the bootable ISO Image below.
- WinPE: Adding PowerShell support to Windows PE – https://msdn.microsoft.com/en-us/library/windows/hardware/dn938380%28v=vs.85%29.aspx
Next, we will have to manually create a System Reserved partition to store the Boot file configuration.
:: Create the System Reserved 300MB Partition create partition primary size=300 format fs=ntfs label="System Reserved" quick assign letter=s active
Next, we will use the remaining free space to create an Operating System partition where the Nano Server VHD file will be located and exit DiskPart.
:: Create the Operating System Partition create partition primary format fs=ntfs label="Operating System" quick assign letter=c exit
With the Operating System partition created, we will copy the Nano Server VHD file to the Operating System drive.
:: Copy the NanoServer-Compute.vhd from WindowsPE ISO to C:\ Operating System Drive xcopy D:\VHD\NanoServer-Compute.vhd C:\ /V /F
Next, we will using DiskPart again to attach the Nano Server VHD file as a vDisk volume.
:: Attach the NanoServer.vhd vDisk using Diskpart diskpart select vDisk File=C:\NanoServer-Compute.vhd attach vDisk list volume
To make our life easy, we will assign a drive letter to identify the vDisk volume and exit DiskPart. And this is not the end of it because the attached vDisk volume is still not bootable due to the fact that the System Reserved partition do not have a boot file configuration of this virtual disk volume.
:: Assign a Drive Letter to the NanoServer-Compute.vhd vDisk volume select volume 3 assign letter=v exit
Creating the Boot Configuration File using Windows PE
With the vDisk drive letter assigned and exited the DiskPart, we will change to the vDisk drive and navigate to the Windows\System32 folder. We will use the BCDboot tool and specify the source of the boot environment file that requires to be copied to the System Reserved drive.
:: Create boot file on System Reserved drive V: cd V:\Windows\System32 bcdboot V:\Windows /s S:
If you are interested in understanding BCDBoot, you can refer to this document link below;
- BCDboot Command-Line Options – https://technet.microsoft.com/en-us/library/hh824874.aspx
Once the boot files has created successfully, we will return to DiskPart, detach the virtual disk volume and exit everything for an automatic reboot.
:: Detach the vDisk and exit to reboot diskpart select vDIsk File=C:\NanoServer-Compute.vhd detach vDisk exit exit
Having the first look of Nano Server from vSphere Remote Console
After exiting Windows PE environment and reboot automatically, you can view login screen on your Remote Console.
After logging into the Nano Server through Remote Console, there is nothing much except text information of the Server Configuration. We cannot do anything in here except for the 4 tasks;
1. Navigate using Up and Down arrows
2. Initiate to Log Off using ESCape button
3. Initiate a Restart or Reboot using ConTroL and F6 button together
4. Initiate a Shut down using ConTrol and F12 button
How to manage the Nano Server remotely?
Since it has no Graphical User Interface and it limited on what we can do in remote console, the most preferred method will be using PowerShell to remotely connect to the Nano Server for any management at this stage.
# Verify if the Nano Server is a Trusted Hosts Get-Item ` -Path WSMan:\localhost\Client\TrustedHosts ; # Set the Nano Server IP Address to be a Trusted Hosts Set-Item ` -Path WSMan:\localhost\Client\TrustedHosts ` -Value 192.168.100.14 ` -Force ; # Establish a remote PowerShell Session to the Nano Server Enter-PSSession ` -ComputerName 192.168.100.14 ` -Credential (New-Object ` -TypeName System.Management.Automation.PSCredential ` -ArgumentList "192.168.100.14\Administrator", ` (ConvertTo-SecureString ` -String "Password" ` -AsPlainText ` -Force) ` ) ;
Время на прочтение8 мин
Количество просмотров20K
Представляем первую из пяти статей, посвященных работе с ASP.NET Core: руководство по развертыванию приложения ASP.NET Core на Nano Server со службами IIS.
Первый цикл статей по ASP.NET Core
1. ASP.NET Core на Nano Server.
2. Создание внешнего интерфейса веб-службы для приложения.
3. Создание первого веб-API с использованием ASP.NET Core MVC и Visual Studio.
4. Развертывание веб-приложения в службе приложений Azure с помощью Visual Studio.
5. Ваше первое приложение на Mac c использованием Visual Studio Code.
Введение
Nano Server — это вариант установки Windows Server 2016, который имеет более компактный размер и более широкие возможности обслуживания и обеспечения безопасности по сравнению с Server Core и полным вариантом установки. Более подробная информация приведена в официальной документации по варианту установки Nano Server. Существует три способа начать с ним работу:
1. Загрузить ISO-файл Windows Server 2016 Technical Preview 5 и создать образ Nano Server.
2. Загрузить Nano Server VHD для разработчиков.
3. Создать виртуальную машину в Azure, используя образ Nano Server из Azure Gallery. Если у вас нет учетной записи Azure, вы можете создать бесплатную учетную запись с 30-дневным пробным периодом.
В данном материале используется заранее созданный Nano Server VHD для разработчиков из Windows Server Technical Preview 5.
Далее вам понадобится созданное и опубликованное 64-битное приложение ASP.NET Core.
Подготовка экземпляра Nano Server
Создайте новую виртуальную машину Hyper-V, используя предварительно загруженный файл VHD. Прежде чем войти в систему, необходимо задать пароль администратора. Для этого нужно нажать клавишу F11 в консоли виртуальной машины.
После создания пароля Nano Server может управляться удаленно при помощи PowerShell.
Удаленное подключение к экземпляру Nano Server при помощи PowerShell
Откройте окно PowerShell с повышенными привилегиями, чтобы добавить удаленный экземпляр Nano Server в список TrustedHosts
.
$nanoServerIpAddress = "10.83.181.14"
Set-Item WSMan:\localhost\Client\TrustedHosts "$nanoServerIpAddress" -Concatenate -Force
Примечание: замените переменную $nanoServerIpAddress
на используемый IP-адрес.
После добавления экземпляра Nano Server в список TrustedHosts
выполните удаленное подключение к нему при помощи PowerShell.
$nanoServerSession = New-PSSession -ComputerName $nanoServerIpAddress -Credential ~\Administrator
Enter-PSSession $nanoServerSession
В случае успешного подключения появится командная строка следующего вида:
[10.83.181.14]: PS C:\Users\Administrator\Documents>
Создание каталога общего доступа
Создайте каталог общего доступа в экземпляре Nano Server, чтобы скопировать в него опубликованное приложение. В удаленном сеансе выполните следующие команды:
mkdir C:\PublishedApps\AspNetCoreSampleForNano
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes
net share AspNetCoreSampleForNano=c:\PublishedApps\AspNetCoreSampleForNano /GRANT:EVERYONE`,FULL
После выполнения указанных команд вы сможете открыть каталог общего доступа, введя адрес \\<nanoserver-ip-address>\AspNetCoreSampleForNano
в проводнике на хост-компьютере.
Открытие порта в брандмауэре
Выполните следующие команды в удаленном сеансе, чтобы открыть порт в брандмауэре:
New-NetFirewallRule -Name "AspNet5 IIS" -DisplayName "Allow HTTP on TCP/8000" -Protocol TCP -LocalPort 8000 -Action Allow -Enabled True
Установка IIS
Добавьте поставщика NanoServerPackage
, выбрав его в коллекции PowerShell. После установки и импорта поставщика появится возможность устанавливать пакеты Windows.
Выполните следующие команды в PowerShell:
Install-PackageProvider NanoServerPackage
Import-PackageProvider NanoServerPackage
Install-NanoServerPackage -Name Microsoft-NanoServer-Storage-Package
Install-NanoServerPackage -Name Microsoft-NanoServer-IIS-Package
После установки компонента >Microsoft-NanoServer-Storage-Package
требуется перезагрузка. Это временная процедура и она не будет нужна в будущем.
Чтобы быстро проверить, корректно ли установлены службы IIS, перейдите по адресу http://<nanoserver-ip-address>/
— должна отобразиться стартовая страница. При установке служб IIS создается веб-сайт по умолчанию под названием Default Web Site
, для которого используется порт 80.
Установка модуля ASP.NET Core (ANCM)
Модуль ASP.NET Core — это модуль IIS 7.5+, который отвечает за управление работой прослушивателей (listeners) ASP.NET Core HTTP и передачу запросов к процессам, которыми он управляет. На данный момент установка модуля ASP.NET Core для IIS осуществляется вручную. Потребуется установить пакет .NET Core Windows Server Hosting на устройство с обычной операционной системой (не Nano Server). После установки пакета на компьютер с обычной операционной системой необходимо скопировать следующие файлы в каталог общего доступа, который был создан ранее.
На компьютере с обычной операционной системой (не Nano Server) выполните следующие команды копирования:
copy C:\windows\system32\inetsrv\aspnetcore.dll ``\\<nanoserver-ip-address>\AspNetCoreSampleForNano``
copy C:\windows\system32\inetsrv\config\schema\aspnetcore_schema.xml ``\\<nanoserver-ip-address>\AspNetCoreSampleForNano``
На виртуальной машине Nano Server необходимо скопировать следующие файлы из каталога общего доступа, который был создан ранее, в соответствующее расположение. Выполните следующие команды копирования:
copy C:\PublishedApps\AspNetCoreSampleForNano\aspnetcore.dll C:\windows\system32\inetsrv\
copy C:\PublishedApps\AspNetCoreSampleForNano\aspnetcore_schema.xml C:\windows\system32\inetsrv\config\schema\
Выполните следующий скрипт в удаленном сеансе:
# Backup existing applicationHost.config
copy C:\Windows\System32\inetsrv\config\applicationHost.config C:\Windows\System32\inetsrv\config\applicationHost_BeforeInstallingANCM.config
Import-Module IISAdministration
# Initialize variables
$aspNetCoreHandlerFilePath="C:\windows\system32\inetsrv\aspnetcore.dll"
Reset-IISServerManager -confirm:$false
$sm = Get-IISServerManager
# Add AppSettings section
$sm.GetApplicationHostConfiguration().RootSectionGroup.Sections.Add("appSettings")
# Set Allow for handlers section
$appHostconfig = $sm.GetApplicationHostConfiguration()
$section = $appHostconfig.GetSection("system.webServer/handlers")
$section.OverrideMode="Allow"
# Add aspNetCore section to system.webServer
$sectionaspNetCore = $appHostConfig.RootSectionGroup.SectionGroups["system.webServer"].Sections.Add("aspNetCore")
$sectionaspNetCore.OverrideModeDefault = "Allow"
$sm.CommitChanges()
# Configure globalModule
Reset-IISServerManager -confirm:$false
$globalModules = Get-IISConfigSection "system.webServer/globalModules" | Get-IISConfigCollection
New-IISConfigCollectionElement $globalModules -ConfigAttribute @{"name"="AspNetCoreModule";"image"=$aspNetCoreHandlerFilePath}
# Configure module
$modules = Get-IISConfigSection "system.webServer/modules" | Get-IISConfigCollection
New-IISConfigCollectionElement $modules -ConfigAttribute @{"name"="AspNetCoreModule"}
# Backup existing applicationHost.config
copy C:\Windows\System32\inetsrv\config\applicationHost.config C:\Windows\System32\inetsrv\config\applicationHost_AfterInstallingANCM.config
Примечание: удалите файлы aspnetcore.dll
и aspnetcore_schema.xml
из каталога общего доступа после завершения предыдущего шага.
Установка .NET Core Framework
Если вы опубликовали переносимое приложение, платформа .NET Core должна быть установлена на целевом компьютере. Выполните следующие скрипты в удаленном сеансе Powershell, чтобы установить .NET Framework на виртуальной машине Nano Server:
$SourcePath = "https://go.microsoft.com/fwlink/?LinkID=809115"
$DestinationPath = "C:\dotnet"
$EditionId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'EditionID').EditionId
if (($EditionId -eq "ServerStandardNano") -or
($EditionId -eq "ServerDataCenterNano") -or
($EditionId -eq "NanoServer") -or
($EditionId -eq "ServerTuva")) {
$TempPath = [System.IO.Path]::GetTempFileName()
if (($SourcePath -as [System.URI]).AbsoluteURI -ne $null)
{
$handler = New-Object System.Net.Http.HttpClientHandler
$client = New-Object System.Net.Http.HttpClient($handler)
$client.Timeout = New-Object System.TimeSpan(0, 30, 0)
$cancelTokenSource = [System.Threading.CancellationTokenSource]::new()
$responseMsg = $client.GetAsync([System.Uri]::new($SourcePath), $cancelTokenSource.Token)
$responseMsg.Wait()
if (!$responseMsg.IsCanceled)
{
$response = $responseMsg.Result
if ($response.IsSuccessStatusCode)
{
$downloadedFileStream = [System.IO.FileStream]::new($TempPath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
$copyStreamOp = $response.Content.CopyToAsync($downloadedFileStream)
$copyStreamOp.Wait()
$downloadedFileStream.Close()
if ($copyStreamOp.Exception -ne $null)
{
throw $copyStreamOp.Exception
}
}
}
}
else
{
throw "Cannot copy from $SourcePath"
}
[System.IO.Compression.ZipFile]::ExtractToDirectory($TempPath, $DestinationPath)
Remove-Item $Temp</code>
Path
}
Публикация приложения
Скопируйте опубликованное приложение в каталог общего доступа. Возможно, потребуется внести изменения в файл web.config
, чтобы указать каталог, в который извлечен файл dotnet.exe
. Другой способ — скопировать файл dotnet.exe
в тот же каталог.
Пример файла web.config
в ситуации, когда файл dotnet.exe
не скопирован в тот же каталог:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="C:\dotnet\dotnet.exe" arguments=".\AspNetCoreSampleForNano.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />
</system.webServer>
</configuration>
Выполните следующие команды в удаленной сессии, чтобы создать новый веб-сайт в IIS для опубликованного приложения. В этом скрипте для упрощения используется DefaultAppPool
. Более подробная информация о работе с пулом приложений приведена в статье Application Pools.
Import-module IISAdministration
New-IISSite -Name "AspNetCore" -PhysicalPath c:\PublishedApps\AspNetCoreSampleForNano -BindingInformation "*:8000:"
Известная проблема в работе .NET Core CLI в Nano Server и способ ее обхода
Если используется Nano Server Technical Preview 5 c .NET Core CLI, необходимо скопировать файлы DLL из каталога c:\windows\system32\forwarders
в каталог c:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.0\
и в каталог двоичных файлов .NET Core c:\dotnet
(в данном примере). Это вызвано ошибкой, которая устранена в более новых версиях.
Если используется команда dotnet publish
, скопируйте также файлы DLL из каталога c:\windows\system32\forwarders
в каталог публикации.
Если система Nano Server Technical Preview 5 была обновлена или изменена, повторите данную процедуру, так как файлы DLL также могли быть обновлены.
Запуск приложения
Опубликованное веб-приложение должно быть доступно в браузере по адресу http://<nanoserver-ip-address>:8000
. Если ведение журнала сконфигурировано так, как указано в разделе Создание и перенаправление логов, все журналы доступны в каталоге C:\PublishedApps\AspNetCoreSampleForNano\logs
.
В данном материале используется предварительный выпуск варианта установки Nano Server, который доступен в Windows Server Technical Preview 5. Программное обеспечение на виртуальном образе жесткого диска может использоваться только для целей внутренней демонстрации и тестирования. Данное программное обеспечение не предназначено для использования в производственной среде. Дату окончания действия ознакомительной версии можно узнать здесь.