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 which is not loaded by default, the using assembly command should be added first. For example, if a script is to work with the Windows Presentation Framework, the following might be useful:

# Load the the Windows Presentation Framework 
using assembly PresentationFramework 
# Use the System.Windows namespace 
using namespace System.Windows 
 
$window = New-Object Window 
$window.Height = 100 
$window.Width = 150 
# Create a System.Windows.Controls.Button object 
$button = New-Object Controls.Button 
$button.Content = 'Close' 
$button.Add_Click( { $window.Close() } ) 
$window.Content = $button 
$window.ShowDialog() 

PowerShell only allows one using namespace statement in the console. The last used is valid. In a script, more than one using namespace statement may be declared.

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

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