Using namespaces

Many of the examples used in this chapter have involved typing the full namespace path to get to a class name. This requirement can be eased with the using keyword.

For example, if a script does a lot of work with the System.Net.NetworkInformation class, the requirement to type the namespace every time can be removed. This allows the System.Net.NetworkInformation.NetworkInterface class to be used with a much shorter type name:

using namespace System.Net.NetworkInformation 

With this statement in place, classes can be used without the long namespace:

[NetworkInterface]::GetAllNetworkInterfaces() 

If the namespace is present within an assembly that isn't loaded by default, the using assembly command should be added first. For example, if a script is to work with Windows Presentation Framework in Windows PowerShell, the following might be useful:

# Load the Windows Presentation Framework 
using assembly PresentationFramework 
# Use the System.Windows namespace 
using namespace System.Windows 
 
$window = [Window]@{
    Height = 100 
    Width = 150
} # Create a System.Windows.Controls.Button object $button = [Controls.Button]@{ Content = 'Close'
} $button.Add_Click( { $window.Close() } ) $window.Content = $button $window.ShowDialog()
GUIs and PowerShell Core

Like System.Windows.Forms, the Windows Presentation Framework is not available in .NET Core at this time. Both are planned to reappear in .NET Core 3 in 2019 (on Windows systems only).

PowerShell only allows one using namespace statement line in the console. If the statements are made on different lines, only the last will be valid. It is possible to use more than one namespace in the console by separating the statements with ;. This is demonstrated in the following code block:

PS> using namespace System.IO; using namespace System.Text
PS> [File].FullName
System.IO.File
PS> [StringBuilder].FullName
System.Text.StringBuilder

In a script, using namespace statements may appear across as many lines as required.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.15