Getting Started with Nano Server
上QQ阅读APP看书,第一时间看更新

Run commands on first boot

SetupComplete.cmd is a command file that, if found on boot by Windows under this location (C:\Windows\Setup\Scripts\), will be executed once and then never again, even if it's still in the same location afterward.

In the following example, we are setting a static IP address using command prompt. The trick here is that we are executing a PowerShell command by adding PowerShell.exe in the .cmd file. Because there is no PowerShell environment here, we follow this by adding -command and everything after that is a single command placed between quotation marks. It's very important for the command to be a single line, because every PowerShell.exe has its own environment. Therefore, we put everything related to setting the static IP address into one PowerShell command.

Create a SetupComplete.cmd file and copy the following command:

powershell.exe -command "Import-Module C:\windows\system32\windowspowershell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1; Import-Module C:\windows\system32\WindowsPowerShell\v1.0\Modules\NetAdapter\NetAdapter.psd1; $ifa = (Get-NetAdapter -Name Ethernet).ifalias; netsh interface ip set address $ifa static 192.168.100.11" 

In the previous example, we imported the module that is responsible for the utility module called (Microsoft.PowerShell.Utility.psd1), and then we imported another module called NetAdapter.psd1, because we are using Get-NetAdapter including the ifalias parameter. Then we specified netsh interface ip and finally, we set the static IP address 192.168.100.11.

This is a very nice trick for setting once at Windows boot only.

Another command could be running a scheduling task, for example where you can create a scheduling task and add it to the SetupComplete.cmd file as well, so it would be an excellent idea to use any one-time operation that you want to setup on first boot with SetupComplete.cmd.

To copy SetupComplete.cmd into the Server VHD(X) image, you need to use the following DISM commands:

From an elevated command prompt, run the following command:

dism /Mount-Image /ImageFile:.\NanoServer.vhdx /Index:1 /MountDir:.\mountdir 

Create the Setup and Scripts folders and then copy in the Setupcomplete.cmd file:

md .\mountdir\Windows\Setup 
md .\mountdir\Windows\Setup\Scripts
copy .\SetupComplete.cmd .\mountdir\Windows\Setup\Scripts

Finally, unmount the VHD(X) image by running the following command:

dism /Unmount-Image /MountDir:.\mountdir /Commit