開發 Nano 伺服器的 PowerShell CmdletDeveloping PowerShell Cmdlets for Nano Server

適用於︰Windows Server 2016Applies To: Windows Server 2016

重要

從 Windows Server 版本 1709 開始,Nano Server 僅以容器基礎 OS 映像的形式來提供。Starting in Windows Server, version 1709, Nano Server will be available only as a container base OS image. 請查看 Nano Server 的變更以了解這代表的意義。Check out Changes to Nano Server to learn what this means.

概觀Overview

Nano Server 預設會在所有 Nano Server 安裝中包含 PowerShell Core。Nano Server includes PowerShell Core by default in all Nano Server installations. PowerShell Core 是縮減版 PowerShell,建置在 .NET Core 上,並於 Nano Server 和 Windows IoT 核心版等縮減版 Windows 上執行。PowerShell Core is a reduced-footprint edition of PowerShell that is built on .NET Core and runs on reduced-footprint editions of Windows, such as Nano Server and Windows IoT Core. PowerShell Core 的運作方式與其他 PowerShell 版本 (例如 Windows Server 2016 上執行的 Windows PowerShell) 的運作方式相同。PowerShell Core functions in the same way as other editions of PowerShell, such as Windows PowerShell running on Windows Server 2016. 不過,縮減版 Nano Server 表示並非 Windows Server 2016 中的所有 PowerShell 功能都可供 Nano Server 上的 PowerShell Core 使用。However, the reduced footprint of Nano Server means that not all PowerShell features from Windows Server 2016 are available in PowerShell Core on Nano Server.

如果您有想在 Nano Server 上執行的現成 PowerShell Cmdlet,或要開發新的 Cmdlet 以用於該目的,本主題包含的秘訣和建議有助於簡化工作。If you have existing PowerShell cmdlets that you'd like to run on Nano Server, or are developing new ones for that purpose, this topic includes tips and suggestions that should help make that easier.

PowerShell 版本PowerShell editions

從 5.1 版開始,PowerShell 提供代表各種功能集和平台相容性的不同版本。Starting with version 5.1, PowerShell is available in different editions which denote varying feature sets and platform compatibility.

  • Desktop Edition︰建置在 .NET Framework 上,並與 Server Core 和 Windows Desktop 等完整版 Windows 上執行之目標 PowerShell 版本的指令碼和模組相容。Desktop Edition: Built on .NET Framework and provides compatibility with scripts and modules targeting versions of PowerShell running on full footprint editions of Windows such as Server Core and Windows Desktop.
  • Core Edition︰建置在 .NET Core 上,並與 Nano Server 和 Windows IoT 等縮減版 Windows 上執行之目標 PowerShell 版本的指令碼和模組相容。Core Edition: Built on .NET Core and provides compatibility with scripts and modules targeting versions of PowerShell running on reduced footprint editions of Windows such as Nano Server and Windows IoT.

$PSVersionTable 的 PSEdition 屬性會顯示正在執行的 PowerShell 版本。The running edition of PowerShell is shown in the PSEdition property of $PSVersionTable.

$PSVersionTable  

Name                           Value  
----                           -----  
PSVersion                      5.1.14300.1000  
PSEdition                      Desktop  
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}  
CLRVersion                     4.0.30319.42000  
BuildVersion                   10.0.14300.1000  
WSManStackVersion              3.0  
PSRemotingProtocolVersion      2.3  
SerializationVersion           1.1.0.1  

模組作者可以使用 CompatiblePSEditions 模組資訊清單金鑰,來宣告其模組與一或多個 PowerShell 版本相容。Module authors can declare their modules to be compatible with one or more PowerShell editions using the CompatiblePSEditions module manifest key. 只有 PowerShell 5.1 或更新版本才支援此金鑰。This key is only supported on PowerShell 5.1 or later.

New-ModuleManifest -Path .\TestModuleWithEdition.psd1 -CompatiblePSEditions Desktop,Core -PowerShellVersion 5.1  
$moduleInfo = Test-ModuleManifest -Path \TestModuleWithEdition.psd1  
$moduleInfo.CompatiblePSEditions  
Desktop  
Core  

$moduleInfo | Get-Member CompatiblePSEditions  

   TypeName: System.Management.Automation.PSModuleInfo  

Name                 MemberType Definition  
----                 ---------- ----------  
CompatiblePSEditions Property   System.Collections.Generic.IEnumerable[string] CompatiblePSEditions {get;}  

取得可用的模組清單時,您可以依 PowerShell 版本篩選清單。When getting a list of available modules, you can filter the list by PowerShell edition.

Get-Module -ListAvailable | ? CompatiblePSEditions -Contains "Desktop"  

    Directory: C:\Program Files\WindowsPowerShell\Modules  


ModuleType Version    Name                                ExportedCommands  
---------- -------    ----                                ----------------  
Manifest   1.0        ModuleWithPSEditions  

Get-Module -ListAvailable | ? CompatiblePSEditions -Contains "Core" | % CompatiblePSEditions  
Desktop  
Core  

指令碼作者可在 #requires 陳述式上使用 PSEdition 參數,只允許指令碼在相容的 PowerShell 版本上執行。Script authors can prevent a script from executing unless it is run on a compatible edition of PowerShell using the PSEdition parameter on a #requires statement.

Set-Content C:\script.ps1 -Value "#requires -PSEdition Core  
Get-Process -Name PowerShell"  
Get-Content C:\script.ps1  
#requires -PSEdition Core  
Get-Process -Name PowerShell  

C:\script.ps1  
C:\script.ps1 : The script 'script.ps1' cannot be run because it contained a "#requires" statement for PowerShell editions 'Core'. The edition of PowerShell that is required by the script does not match the currently running PowerShell Desktop edition.  
At line:1 char:1  
+ C:\script.ps1  
+ ~~~~~~~~~~~~~  
    + CategoryInfo          : NotSpecified: (script.ps1:String) [], RuntimeException  
    + FullyQualifiedErrorId : ScriptRequiresUnmatchedPSEdition  

安裝 Nano ServerInstalling Nano Server

安裝 Nano Server (也就是本文的最上層主題) 中提供在虛擬或實體機器上安裝 Nano Server 的快速入門和詳細步驟。Quick-start and detailed steps for installing Nano Server on virtual or physical machines are provided in Install Nano Server, which is the parent topic for this one.

注意

若要在 Nano Server 上正確開發,使用 New-NanoServerImage 的 -Development 參數來安裝 Nano Server 會很有用。For development work on Nano Server, you might find it useful to install Nano Server by using the -Development parameter of New-NanoServerImage. 這會啟用未簽署驅動程式的安裝、複製偵錯工具二進位檔、開啟偵錯用的連接埠、啟用測試簽署,以及啟用 AppX 套件的安裝,而不需要開發人員授權。This will enable installation of unsigned drivers, copy debugger binaries, open a port for debugging, enable test signing and enable installation of AppX packages without a developer license. 例如:For example:

New-NanoServerImage -DeploymentType Guest -Edition Standard -MediaPath \\Path\To\Media\en_us -BasePath .\Base -TargetPath .\NanoServer.wim -Development

決定 Cmdlet 實作的類型Determining the type of cmdlet implementation

PowerShell 支援 Cmdlet 的一些實作類型,而您所使用的類型會決定在 Nano Server 上正確建立或移植所需的程序和工具。PowerShell supports a number of implementation types for cmdlets, and the one you've used determines the process and tools involved in creating or porting it to work on Nano Server. 支援的實作類型包括:Supported implementation types are:

  • CIM - 包含 CIM (WMIv2) 提供者上分層的 CDXML 檔案CIM - consists of CDXML files layered over CIM (WMIv2) providers
  • .NET - 包含實作 Managed Cmdlet 介面的 .NET 組件,通常以 C# 撰寫.NET - consists of .NET assemblies implementing managed cmdlet interfaces, typically written in C#
  • PowerShell 指令碼 - 包含以 PowerShell 語言撰寫的指令碼模組 (.psm1) 或指令碼 (.ps1)PowerShell Script - consists of script modules (.psm1) or scripts (.ps1) written in the PowerShell language

如果您不確定要移植之現有 Cmdlet 所使用的實作,請安裝您的產品或功能,然後在下列其中一個位置尋找 PowerShell 模組資料夾:If you're not sure which implementation you've used for existing cmdlets you want to port, install your product or feature and then look for the PowerShell module folder in one of the following locations:

  • %windir%\system32\WindowsPowerShell\v1.0\Modules%windir%\system32\WindowsPowerShell\v1.0\Modules
  • %ProgramFiles%\WindowsPowerShell\Modules%ProgramFiles%\WindowsPowerShell\Modules
  • %UserProfile%\Documents\WindowsPowerShell\Modules%UserProfile%\Documents\WindowsPowerShell\Modules
  • <您的產品安裝位置><your product installation location>

    在這些位置確認下列詳細資料:Check in these locations for these details:

    • CIM Cmdlet 的副檔名為 .cdxml。CIM cmdlets have .cdxml file extensions.
    • .NET Cmdlet 的副檔名為 .dll,或已安裝 .psd1 檔案所列 GAC 之 RootModule、ModuleToProcess 或 NestedModules 欄位下的組件。.NET cmdlets have .dll file extensions, or have assemblies installed to the GAC listed in the .psd1 file under the RootModule, ModuleToProcess, or NestedModules fields.
  • PowerShell 指令碼 Cmdlet 的副檔名為 .psm1 或 .ps1。PowerShell script cmdlets have .psm1 or .ps1 file extensions.

移植 CIM CmdletPorting CIM cmdlets

一般而言,這些 Cmdlet 應該可在 Nano Server 中正常運作,而不需要進行任何轉換。Generally, these cmdlets should work in Nano Server without any conversion necessary. 不過,如果尚未移植基礎 WMI v2 提供者,您必須先將它移植才能在 Nano Server 上執行。However, you must port the underlying WMI v2 provider to run on Nano Server if that has not already been done.

建置適用於 Nano Server 的 C++Building C++ for Nano Server

若要讓 C++ DLL 在 Nano Server 上正常運作,請針對 Nano Server (而不是特定版本) 加以編譯。To get C++ DLLs working on Nano Server, compile them for Nano Server rather than for a specific edition.

如需在 Nano Server 上開發 C++ 的先決條件和逐步解說,請參閱 Developing Native Apps on Nano Server (在 Nano Server 上開發原生應用程式)。For prerequisites and a walkthrough of developing C++ on Nano Server, see Developing Native Apps on Nano Server.

移植 .NET CmdletPorting .NET cmdlets

Nano Server 支援大部分的 C# 程式碼。Most C# code is supported on Nano Server. 您可以使用 ApiPort 掃描是否有不相容的 API。You can use ApiPort to scan for incompatible APIs.

Powershell Core SDKPowershell Core SDK

PowerShell Gallery (PowerShell 資源庫) 中提供模組 "Microsoft.PowerShell.NanoServer.SDK",使用以 Nano Server 隨附的 CoreCLR 和 PowerShell Core 版本為目標的 Visual Studio 2015 Update 2 來加速 .NET Cmdlet 的開發。The module "Microsoft.PowerShell.NanoServer.SDK" is available in the PowerShell Gallery to facilitate developing .NET cmdlets using Visual Studio 2015 Update 2 that target the versions of CoreCLR and PowerShell Core available in Nano Server. 您可以使用 PowerShellGet 搭配下列命令來安裝模組:You can install the module using PowerShellGet with this command:

Find-Module Microsoft.PowerShell.NanoServer.SDK -Repository PSGallery | Install-Module -Scope <scope>

PowerShell Core SDK 模組所公開的 Cmdlet,可設定正確的 CoreCLR 和 PowerShell Core 參考組件、在 Visual Studio 2015 中建立以這些參考組件為目標的 C# 專案,以及在 Nano Server 電腦上設定遠端偵錯工具,讓開發人員可以偵錯 Nano Server 上以 Visual Studio 2015 遠端執行的 .NET Cmdlet。The PowerShell Core SDK module exposes cmdlets to set up the correct CoreCLR and PowerShell Core reference assemblies, create a C# project in Visual Studio 2015 targeting those reference assemblies, and set up the remote debugger on a Nano Server machine so that developers can debug their .NET cmdlets running on Nano Server remotely in Visual Studio 2015.

PowerShell Core SDK 模組需要 Visual Studio 2015 Update 2。The PowerShell Core SDK module requires Visual Studio 2015 Update 2. 如果您未安裝 Visual Studio 2015,您可以安裝 Visual Studio Community 2015If you do not have Visual Studio 2015 installed, you can install Visual Studio Community 2015.

SDK 模組也相依於要在 Visual Studio 2015 中安裝的下列功能:The SDK module also depends on the following feature to be installed in Visual Studio 2015:

  • Windows 及 Web 程式開發 -> 通用 Windows 應用程式開發工具 -> 工具 (1.3.1) 及 Windows 10 SDKWindows and Web Development -> Universal Windows App Development Tools -> Tools (1.3.1) and Windows 10 SDK

使用 SDK 模組之前,請先檢閱您的 Visual Studio 安裝,以確保符合這些先決條件。Review your Visual Studio installation before using the SDK module to ensure these prerequisites are satisfied. 請確定您在 Visual Studio 安裝期間選取並安裝上述功能,或修改您現有的 Visual Studio 2015 安裝以安裝此功能。Make sure you select to install the above feature during the Visual Studio installation, or modify your existing Visual Studio 2015 installation to install it.

PowerShell Core SDK 模組包含下列 Cmdlet:The PowerShell Core SDK module includes the following cmdlets:

  • New-NanoCSharpProject︰建立新的 Visual Studio C# 專案,該專案是以 Windows Server 2016 版 Nano Server 隨附的 CoreCLR 和 PowerShell Core 為目標。New-NanoCSharpProject: Creates a new Visual Studio C# project targeting CoreCLR and PowerShell Core included in the Windows Server 2016 release of Nano Server.
  • Show-SdkSetupReadMe︰在檔案總管中開啟 SDK 根資料夾,然後開啟 README.txt 檔案手動進行安裝。Show-SdkSetupReadMe: Opens the SDK root folder in File Explorer and opens the README.txt file for manual setup.
  • Install-RemoteDebugger︰在 Nano Server 電腦上安裝及設定 Visual Studio 遠端偵錯工具。Install-RemoteDebugger: Installs and configures the Visual Studio remote debugger on a Nano Server machine.
  • Start-RemoteDebugger︰在執行 Nano Server 的遠端電腦上啟動遠端偵錯工具。Start-RemoteDebugger: Starts the remote debugger on a remote machine running Nano Server.
  • Stop-RemoteDebugger︰在執行 Nano Server 的遠端電腦上停止遠端偵錯工具。Stop-RemoteDebugger: Stops the remote debugger on a remote machine running Nano Server.

如需如何使用這些 Cmdlet 的詳細資訊,請在安裝並匯入模組之後,在每個 Cmdlet 上執行 Get-Help,如下所示:For detailed information about how to use those cmdlets, run Get-Help on each cmdlet after installing and importing the module as follows:

Get-Command -Module Microsoft.PowerShell.NanoServer.SDK | Get-Help -Full

搜尋相容的 APISearching for compatible APIs

您可以在 API 類別目錄中搜尋 .NET Core,或反組譯 Core CLR 參考組件。You can search in the API catalog for .NET Core or disassemble Core CLR reference assemblies. 如需 .NET API 之平台可攜性的詳細資訊,請參閱 Platform PortabilityFor more information about platform portability of .NET APIs, see Platform Portability

PInvokePInvoke

在 Nano Server 使用的 Core CLR 中,已將一些基本 DLL (例如 kernel32.dll 和 advapi32.dll) 分割成多個 API 集合,因此您必須確定 PInvoke 參考正確的 API。In the Core CLR that Nano Server uses, some fundamental DLLs such as kernel32.dll and advapi32.dll were split into numerous API sets, so you'll need to ensure that your PInvokes reference the correct API. 任何不相容都會顯示為執行階段錯誤。Any incompatibility will manifest as a runtime error.

如需 Nano Server 支援的原生 API 清單,請參閱 Nano Server APIFor a list of native APIs supported on Nano Server, see Nano Server APIs.

建置適用於 Nano Server 的 C#Building C# for Nano Server

在 Visual Studio 2015 中使用 New-NanoCSharpProject 建立 C# 專案之後,您可以直接在 Visual Studio 中按一下 [組建] 功能表,然後選取 [建置專案][建置方案] 加以建置。Once a C# project is created in Visual Studio 2015 by using New-NanoCSharpProject, you can simply build it in Visual Studio by clicking the Build menu and selecting Build Project or Build Solution. 產生的組件會以 Nano Server 隨附的正確 CoreCLR 和 PowerShell Core 為目標,而且您只能將這些組件複製到執行 Nano Server 的電腦,再加以使用。The generated assemblies will be targeting the correct CoreCLR and PowerShell Core shipped in Nano Server, and you can just copy the assemblies to a computer running Nano Server and use them.

建置適用於 Nano Server 的 Managed C++ (CPP/CLI)Building managed C++ (CPP/CLI) for Nano Server

CoreCLR 不支援 Managed C++。Managed C++ is not supported for CoreCLR. 移植到 CoreCLR 時,請在 C# 中重寫 Managed C++ 程式碼,並透過 PInvoke 進行所有原生呼叫。When porting to CoreCLR, rewrite managed C++ code in C# and make all native calls through PInvoke.

移植 PowerShell 指令碼 CmdletPorting PowerShell script cmdlets

PowerShell Core 具有與其他 PowerShell 版本完全相同的PowerShell 語言,包括在 Windows Server 2016 和 Windows 10 上執行的版本。PowerShell Core has full PowerShell language parity with other editions of PowerShell, including the edition running on Windows Server 2016 and Windows 10. 不過,將 PowerShell 指令碼 Cmdlet 移植到 Nano Server 時,請注意下列因素:However, when porting PowerShell script cmdlets to Nano Server, keep these factors in mind:

  • 是否相依於其他 Cmdlet?Are there dependencies on other cmdlets? 如果是的話,這些 Cmdlet 是否可在 Nano Server 上使用?If so, are those cmdlets available on Nano Server. 如需哪些 Cmdlet 無法使用的資訊,請參閱 Nano Server 上的 PowerShellSee PowerShell on Nano Server for information about what is not available.
  • 如果相依於在執行階段載入的組件,是否仍然可以運作?If you have dependencies on assemblies that are loaded at runtime, will they still work?
  • 如何從遠端偵錯指令碼?How can you debug the script remotely?
  • 如何從 WMI .Net 移轉至 MI .Net?How can you migrate from WMI .Net to MI .Net?

內建 Cmdlet 的相依性Dependency on built-in cmdlets

並非 Windows Server 2016 中的所有 Cmdlet 都可在 Nano Server 上使用 (請參閱 Nano Server 上的 PowerShell)。Not all cmdlets in Windows Server 2016 are available on Nano Server (see PowerShell on Nano Server). 最佳做法是設定 Nano Server 虛擬機器,並探索您需要的 Cmdlet 是否可用。The best approach is to set up a Nano Server virtual machine and discover whether the cmdlets you need are available. 若要這樣做,請執行 Enter-PSSession 以連線到目標 Nano Server,然後執行 Get-Command -CommandType Cmdlet, Function 以取得可用 Cmdlet 的清單。To do this, run Enter-PSSession to connect to the target Nano Server and then run Get-Command -CommandType Cmdlet, Function to get the list of available cmdlets.

考慮使用 PowerShell 類別Consider using PowerShell classes

Nano Server 支援 Add-Type 以編譯內嵌 C# 程式碼。Add-Type is supported on Nano Server for compiling inline C# code. 如果您要撰寫新的程式碼或移植現有的程式碼,您也可以考慮使用 PowerShell 類別來定義自訂類型。If you're writing new code or porting existing code, you might also consider using PowerShell classes to define custom types. 您可以將 PowerShell 類別用於屬性包案例及列舉。You can use PowerShell classes for property bag scenarios as well as for Enums. 如果您需要執行 PInvoke,請透過 C# 使用 Add-Type 或在先行編譯組件中執行。If you need to do a PInvoke, do this via C# using Add-Type or in a pre-compiled assembly.
下列範例示範如何使用 Add-Type:Here's a sample showing the use of Add-Type:

Add-Type -ReferencedAssemblies ([Microsoft.Management.Infrastructure.Ciminstance].Assembly.Location) -TypeDefinition @'  
public class TestNetConnectionResult  
{  
   // The compute name  
   public string ComputerName = null;  
   // The Remote IP address used for connectivity  
   public System.Net.IPAddress RemoteAddress = null;  
}  
'@  
# Create object and set properties  
$result = New-Object TestNetConnectionResult  
$result.ComputerName = "Foo"  
$result.RemoteAddress = 1.1.1.1  

下列範例示範如何在 Nano Server 上使用 PowerShell 類別:This sample shows using PowerShell classes on Nano Server:

class TestNetConnectionResult    
{    
   # The compute name  
  [string] $ComputerName    

  #The Remote IP address used for connectivity    
  [System.Net.IPAddress] $RemoteAddress  
}  
# Create object and set properties  
$result = [TestNetConnectionResult]::new()  
$result.ComputerName = "Foo"  
$result.RemoteAddress = 1.1.1.1  

從遠端偵錯指令碼Remotely debugging scripts

若要從遠端偵錯指令碼,請從 PowerShell ISE 使用 Enter-PSsession 連線到遠端電腦。To remotely debug a script, connect to the remote computer using Enter-PSsession from the PowerShell ISE. 進入工作階段之後,您就可以執行 psedit <file_path>,隨即會在您的本機 PowerShell ISE 中開啟此檔案的複本。Once inside the session, you can run psedit <file_path> and a copy of the file will be open in your local PowerShell ISE. 然後,您可以設定中斷點來偵錯指令碼,就像是在本機執行一樣。Then, you can debug the script as if it were running locally by setting breakpoints. 此外,您對此檔案所做的任何變更都會儲存在遠端版本中。Also, any changes you make to this file will be saved in the remote version.

從 WMI .NET 移轉至 MI .NETMigrating from WMI .NET to MI .NET

不支援 WMI.NET,因此使用舊版 API 的所有 Cmdlet 都必須移轉至支援的 WMI API:MI.NETWMI .NET is not supported, so all cmdlets using the old API must migrate to the supported WMI API: MI. NET. 您可以直接透過 C# 或透過 CimCmdlets 模組中的 Cmdlet 來存取 MI .NET。You can access MI .NET directly through C# or through the cmdlets in the CimCmdlets module.

CimCmdlets 模組CimCmdlets module

Nano Server 不支援 WMI v1 Cmdlet (例如 Get-WmiObject),The WMI v1 cmdlets (e.g., Get-WmiObject) are not supported on Nano Server. 但支援 CimCmdlets 模組中的 CIM Cmdlet (例如 Get-CimInstance)。However, the CIM cmdlets (e.g., Get-CimInstance) in the CimCmdlets module are supported. CIM Cmdlet 會非常緊密地對應至 WMI v1 Cmdlet。The CIM cmdlets map pretty closely to the WMI v1 cmdlets. 例如,Get-WmiObject 使用非常類似的參數來與 Get-CimInstance 建立關聯。For example, Get-WmiObject correlates with Get-CimInstance using very similar parameters. 方法引動過程語法稍有不同,但已透過 Invoke-CimMethod 適當記載。Method invocation syntax is slightly different, but is well documented via Invoke-CimMethod. 輸入參數時請小心。Be careful regarding parameter typing. MI .NET 對於方法參數類型有更嚴格的需求。MI .NET has stricter requirements regarding method parameter types.

C# APIC# API

WMI .NET 包裝 WMIv1 介面,而 MI .NET 包裝 WMIv2 (CIM) 介面。WMI .NET wraps the WMIv1 interface, while MI .NET wraps the WMIv2 (CIM) interface. 公開的類別可能會不同,但基礎作業非常類似。The classes exposed might be different, but the underlying operations are very similar. 您可以列舉或取得物件的執行個體,並對其叫用作業以完成工作。You enumerate or get instances of objects and invoke operations on them to accomplish tasks.