Use PowerShell
The Shell Is Calling
The Shell Is Calling
Mar 26th
On April 1st, 2009, Microsoft is putting on a free 24 hour virtual event covering developer-related topics.
There will be 95 live sessions provided via Live Meeting in the following tracks:
PowerShell Community’s own Marco Shaw (MVP) will be presenting the ONLY PowerShell session:
WIN300 Scripting the Microsoft .NET Framework Using Windows PowerShell
Now that PowerShell is part of the Microsoft Common Engineering Criteria, expect to see more and more PowerShell in Microsoft server products. This session looks at how PowerShell can be used to directly access the .NET Framework. Some simple examples are demonstrated, but also more advanced examples of using Windows Presentation Foundation (.NET 3.0) and LINQ (.NET 3.5) are discussed.
You can find more information about this event here or on Marco’s blog.
I’m looking forward to seeing this presentation. Hope to “see” you there! Register now..
Mar 25th
I’m often running too many applications on my workstation, and at least one session of PowerShell is almost always open. I’m regularly jumping back to a PowerShell prompt to try something out, query something from my database, or complete a task.
If I don’t clear out the variables that reference objects I’m done with, the amount of memory used by my PowerShell session increases dramatically, which impacts some other applications that I run. (I know, memory is cheap.. buy more memory. I’ve got a limited budget and I have to prioritize.)
So I’ve written a couple of functions that can help me clear out the extraneous variables and free up some of that memory being used by PowerShell.
The first function (and I’m open to suggestions on the naming here..), Set-SessionVariableList, reads in all the variable names in the global scope and saves them to the AppDomain (so I don’t lose them when I clear out variables). I recommend running this shortly after starting PowerShell or running it from your profile.
Later, when I’m feeling some memory pressure, I can run the second function Remove-NewVariable, which calls Remove-Variable for all variables whose names I did not save in the AppDomain. This removes the references to the objects they represented.
Info Overload: Notice that I said that it removed the references to those objects. Those objects still exist in memory and remain there until the CLR “garbage collects” them, releasing that memory. The CLR has a process to reclaim that “used” memory when there is a need to reuse it or when it is impacting other performance.
Even if you skipped the previous bold section (which is perfectly acceptable), you might have noticed that when you clear out a variable, your memory usage for PowerShell might remain high for a while. My function speeds up the natural “garbage collection” process by calling [System.GC]::Collect(), forcing the CLR to reclaim that memory.
There are a couple of “helper” functions included, Get-SessionVariableList, which will list out the variable names saved, in case you wanted to see which variables were going to be left and Add-SessionVariable, which adds more values to the current list.
Feedback and improvements are always welcome!
PSMDTAG:FAQ Memory
Mar 24th
Since PowerShell is built on .NET, there is a AppDomain (I’ll go into more detail in a later post) which has a lot of information about the .NET environment (what assemblies are loaded, etc..).
One feature that the AppDomain has is to store globally accessible name/value pairs. Normally, variables in PowerShell should handle most of your “in-process” storage needs, but for the times that they don’t, you have your AppDomain.
To access the AppDomain object, you can use the static property CurrentDomain on the System.AppDomain class.
(NOTE: Though I usually refer use the fully qualified namespace, PowerShell does allow you to skip the “System” portion of the namespace. I’m using the full namespace for clarity on the blog, but when typing on the command line, it is easier to skip that.)
PS C:\> [system.appdomain]::CurrentDomain
To save a name/value pair to your AppDomain, you can use the SetData method.
PS C:\> [system.appdomain]::CurrentDomain.SetData(‘ThisIsMyNameOrKey’, (‘This’,'Can’,'Be’,'Any’,'Object’,'Or’,'Collection’) )
Any object or collection can be saved in the AppDomain, and you are not limited to just one.
Accessing those values is just as easy, using the GetData method.
PS C:\> [system.appdomain]::CurrentDomain.GetData(‘ThisIsMyNameOrKey’)
This
Can
Be
Any
Object
Or
Collection
And there we have our collection back.
PSMDTAG:.Net AppDomain
Mar 20th
In our Exploring the .NET Framework series, we’ve covered some terminology, creating instances of objects and calling methods. In today’s installment, we are going to look at using static members – methods and properties. Static methods are methods that a class (or type) make available without needing to create an instance of the class. Similarly, static properties are properties that you can access without needing an instance of the class.
Many classes provide static members supply functionality where it doesn’t make sense to need an object.
The System.Math class contains a couple of static properties, PI and E.
PS C:\scripts\PowerShell> [math]::E
2.71828182845905
PS C:\scripts\PowerShell> [math]::PI
3.14159265358979
Constant values are not the only type of property that you’ll find. The System.AppDomain class has a static property, CurrentDomain, which is an AppDomain instance referring to the current application domain.
PS C:\scripts\PowerShell> [AppDomain]::CurrentDomain.gettype()
IsPublic IsSerial Name BaseType
——– ——– —- ——–
True False AppDomain System.MarshalByRefObject
System.Math also contains a number of static methods that provide a great deal of basic mathematical function.
PS C:\scripts\PowerShell>[Math] | get-member –static –membertype method | select name
Name
—-
Abs
Acos
Asin
Atan
Atan2
BigMul
Ceiling
Cos
Cosh
DivRem
Equals
Exp
Floor
IEEERemainder
Log
Log10
Max
Min
Pow
ReferenceEquals
Round
Sign
Sin
Sinh
Sqrt
Tan
Tanh
Truncate
I wrote a little helper function to get the static method definitions (Get-StaticMethodDefinition), which you can grab from PoshCode.org.
(V2 CTP3 – We can use the trick of using the method name without parenthesis following to get additional information on each of the methods that we are interested in.)
One type of static method that I would like to highlight is the factory method. A factory method is a common way of controlling object creation. At its most basic level, a factory pattern is a method that creates objects of a specified type.
An example of this is the System.Net.WebRequest’s Create method.
PS C:\scripts\PowerShell> $web = [net.webrequest]::create(‘http://www.google.com‘)
PS C:\scripts\PowerShell> $web.gettype()
IsPublic IsSerial Name BaseType
——– ——– —- ——–
True True HttpWebRequest System.Net.WebReq…
The factory method Create used the argument (‘http://www.google.com’) to determine the type of WebRequest object to create. In this case, it created an HttpWebRequest object, which is a more specialized version of the WebRequest for HTTP requests.
Let’s see how it would respond if we passed the Create method a URI with FTP.
PS C:\scripts\PowerShell> $web = [net.webrequest]::create(‘ftp://ftp.google.com’)
PS C:\scripts\PowerShell> $web.gettype()
IsPublic IsSerial Name BaseType
——– ——– —- ——–
True False FtpWebRequest System.Net.WebReq…
As we can see, the WebRequest class created an FtpWebRequest object.
Factory methods provide developers a way to more flexibly support different operations by allowing the static method to determine which object to return.
UPDATE: Joel “Jaykul” Bennet added a V2 advanced function to convert static methods to functions to PoShCode.org and pointed out Oisin Grehan’s blog post about creating functions from static methods (V1 compatible).
I’ve been really happy to receive some of the feedback (positive and constructive criticism) on this series. There is a lot of the .NET Framework to cover, and I’m open to suggestions as to what you would like to know. Please post a comment on the blog or email me at Steve at UsePowerShell.Com.