about_Windows_PowerShell_Compatibility

簡短描述

描述 PowerShell 7 的 Windows PowerShell 相容性功能。

詳細描述

除非模組指令清單指出模組與 PowerShell Core 相容,否則資料夾中的模組 %windir%\system32\WindowsPowerShell\v1.0\Modules 會由 Windows PowerShell 相容性功能載入背景 Windows PowerShell 5.1 進程。

使用相容性功能

使用 Windows PowerShell 相容性功能匯入第一個模組時,PowerShell 會建立名為 的遠端會話,該 WinPSCompatSession 會話會在背景 Windows PowerShell 5.1 進程中執行。 當相容性功能匯入第一個模組時,就會建立此程式。 當移除最後一個這類模組(使用 Remove-Module)或 PowerShell 進程結束時,就會關閉進程。

在工作階段中載入的 WinPSCompatSession 模組是透過隱含遠端處理來使用,並反映在目前的PowerShell會話中。 這是用於PowerShell作業的相同傳輸方法。

將模組匯入 WinPSCompatSession 會話時,隱含遠端會在使用者的 $env:Temp 目錄中產生 Proxy 模組,並將此 Proxy 模組匯入目前的 PowerShell 會話。 這可讓PowerShell偵測模組已使用 Windows PowerShell 相容性功能載入。

建立會話之後,它就可用於無法正確在還原串行化對象上運作的作業。 整個管線會在 Windows PowerShell 中執行,而且只會傳回最終結果。 例如:

$s = Get-PSSession -Name WinPSCompatSession
Invoke-Command -Session $s -ScriptBlock {
  "Running in Windows PowerShell version $($PSVersionTable.PSVersion)"
}

您可以使用兩種方式叫用相容性功能:

  • 使用 UseWindowsPowerShell 參數明確地匯入模組

    Import-Module -Name ScheduledTasks -UseWindowsPowerShell
    
  • 透過模組名稱、路徑或透過命令探索自動載入,以隱含方式匯入 Windows PowerShell 模組。

    Import-Module -Name ServerManager
    Get-AppLockerPolicy -Local
    

    如果尚未載入,當您執行 Get-AppLockerPolicy時,就會自動載入 AppLocker 模組。

Windows PowerShell 兼容性會封鎖載入 PowerShell 組態檔中設定中列出的 WindowsPowerShellCompatibilityModuleDenyList 模組。

這個設定預設值為:

"WindowsPowerShellCompatibilityModuleDenyList":  [
   "PSScheduledJob","BestPractices","UpdateServices"
]

管理隱含模組載入

若要停用 Windows PowerShell 相容性功能的隱含匯入行為,請使用 DisableImplicitWinCompat PowerShell 組態檔中的 設定。 此設定可以新增至 powershell.config.json 檔案。 如需詳細資訊,請參閱 about_powershell_config

此範例示範如何建立組態檔,以停用 Windows PowerShell 相容性的隱含模組載入功能。

$ConfigPath = "$PSHOME\DisableWinCompat.powershell.config.json"
$ConfigJSON = ConvertTo-Json -InputObject @{
  "DisableImplicitWinCompat" = $true
  "Microsoft.PowerShell:ExecutionPolicy" = "RemoteSigned"
}
$ConfigJSON | Out-File -Force $ConfigPath
pwsh -settingsFile $ConfigPath

如需模組相容性的詳細資訊,請參閱 PowerShell 7 模組相容性 清單。

管理 Cmdlet clobbering

Windows PowerShell 相容性功能會使用隱含遠端功能,以相容性模式載入模組。 結果是模組導出的命令優先於目前 PowerShell 7 工作階段中相同名稱的命令。 在 PowerShell 7.0.0 版本中,這包括隨附於 PowerShell 的核心模組。

在 PowerShell 7.1 中,行為已變更,因此下列核心 PowerShell 模組不會受到 clobbered:

  • Microsoft.PowerShell.ConsoleHost
  • Microsoft.PowerShell.Diagnostics
  • Microsoft.PowerShell.Host
  • Microsoft.PowerShell.Management
  • Microsoft.PowerShell.Security
  • Microsoft.PowerShell.Utility
  • Microsoft.WSMan.Management

PowerShell 7.1 也新增了列出其他模組的功能,這些模組不應受到相容性模式的阻礙。

您可以將設定新增 WindowsPowerShellCompatibilityNoClobberModuleList 至 PowerShell 組態檔。 這個設定的值是以逗號分隔的模組名稱清單。 這個設定預設值為:

"WindowsPowerShellCompatibilityNoClobberModuleList": [ ]

限制

Windows PowerShell 兼容性功能:

  1. 只能在 Windows 電腦上本機運作
  2. 需要 Windows PowerShell 5.1
  3. 在串行化 Cmdlet 參數和傳回值上運作,而不是在即時對象上運作
  4. 匯入 Windows PowerShell 遠端會話的所有模組都會共用相同的 Runspace。

關鍵字

about_Windows_PowerShell_Compatibility

另請參閱