about_Using
簡短描述
可讓您指出會話中使用的命名空間。
完整描述
using
語句可讓您指定工作階段中使用的命名空間。 新增命名空間可簡化 .NET 類別和成員的使用方式,並可讓您從腳本模組和元件匯入類別。
using
語句必須位於腳本或模組的任何其他語句之前。 沒有未批注語句可以位於其中,包括參數。
using
語句不得包含任何變數。
using
語句不應該與using:
變數的範圍修飾詞混淆。 如需詳細資訊,請參閱 about_Remote_Variables。
命名空間語法
若要指定要解析類型的 .NET 命名空間:
using namespace <.NET-namespace>
指定命名空間可讓您更輕鬆地依其簡短名稱參考型別。
模組語法
若要從 PowerShell 模組載入類別:
using module <module-name>
的值 <module-name>
可以是模組名稱、完整模組規格或模組檔案的路徑。
當 <module-name>
是路徑時,路徑可以是完整或相對路徑。 相對於包含 using 語句的腳本,會解析相對路徑。
當 是名稱或模組規格時 <module-name>
,PowerShell 會搜尋 PSModulePath 中的指定模組。
模組規格是具有下列索引鍵的哈希表。
ModuleName
- 必填 指定模組名稱。GUID
- 選 指定模組的 GUID。- 您也可以指定下列三個索引鍵的其中一個。 這些金鑰無法一起使用。
ModuleVersion
- 指定模組的最低可接受版本。RequiredVersion
- 指定模組的確切必要版本。MaximumVersion
- 指定模組可接受的最大版本。
語句會 using module
從文本模組或二進位模組的根模組 (ModuleToProcess
) 匯入類別。 它不會一致地匯入巢狀模組中定義的類別,也不會一致地匯入腳本中以點來源為來源的類別。 您想要供模組外部使用者使用的類別應該定義在根模組中。
在腳本模組的開發期間,通常會變更程式碼,然後使用 Force 參數載入新版本的模組Import-Module
。 這僅適用於根模組中的函式變更。 Import-Module
不會重載任何巢狀模組。 此外,也無法載入任何更新的類別。
若要確保您執行的是最新版本,您必須使用 Remove-Module
Cmdlet 卸除模組。 Remove-Module
會移除根模組、所有巢狀模組,以及模組中定義的任何類別。 然後,您可以使用 和 using module
語句來重載模組和類別Import-Module
。
元件語法
若要從 .NET 元件預先載入類型:
using assembly <.NET-assembly-path>
載入元件會在剖析時,將 .NET 類型從該元件預先載入腳本。 這可讓您建立新的 PowerShell 類別,以使用預先載入的元件中的類型。
如果您未建立新的 PowerShell 類別,請改用 Add-Type
Cmdlet。 如需詳細資訊,請參閱 Add-Type。
範例
範例 1 - 新增 typename 解析的命名空間
下列腳本會取得 「Hello World」 字串的密碼編譯哈希。
請注意和 using namespace System.Text
如何簡化 和 中 [Stream]
System.Text
[MemoryStream]
對 的System.IO
參考。[UnicodeEncoding]
using namespace System.IO
using namespace System.Text
using namespace System.IO
[string]$string = "Hello World"
## Valid values are "SHA1", "SHA256", "SHA384", "SHA512", "MD5"
[string]$algorithm = "SHA256"
[byte[]]$stringbytes = [UnicodeEncoding]::Unicode.GetBytes($string)
[Stream]$memorystream = [MemoryStream]::new($stringbytes)
$hashfromstream = Get-FileHash -InputStream $memorystream `
-Algorithm $algorithm
$hashfromstream.Hash.ToString()
範例 2 - 從文稿模組載入類別
在此範例中,我們有一個名為 CardGames 的 PowerShell 腳本模組,其定義下列類別:
- CardGames.Deck
- CardGames.Card
Import-Module
#requires
和語句只會匯入模組函式、別名和變數,如模組所定義。 類別不會匯入。 命令會 using module
匯入模組,並同時載入類別定義。
using module CardGames
using namespace CardGames
[Deck]$deck = [Deck]::new()
$deck.Shuffle()
[Card[]]$hand1 = $deck.Deal(5)
[Card[]]$hand2 = $deck.Deal(5)
[Card[]]$hand3 = $deck.Deal(5)
範例 3 - 從元件載入類別
此範例會載入元件,使其類別可用來建立新的PowerShell類別。 下列腳本會建立衍生自 DirectoryContext 類別的新 PowerShell 類別。
using assembly 'C:\Program Files\PowerShell\7\System.DirectoryServices.dll'
using namespace System.DirectoryServices.ActiveDirectory
class myDirectoryClass : System.DirectoryServices.ActiveDirectory.DirectoryContext
{
[DirectoryContext]$domain
myDirectoryClass([DirectoryContextType]$ctx) : base($ctx)
{
$this.domain = [DirectoryContext]::new([DirectoryContextType]$ctx)
}
}
$myDomain = [myDirectoryClass]::new([DirectoryContextType]::Domain)
$myDomain
domain Name UserName ContextType
------ ---- -------- -----------
System.DirectoryServices.ActiveDirectory.DirectoryContext Domain