<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>JRICH&#039;s Brain Dump</title>
	<atom:link href="http://jrich523.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jrich523.wordpress.com</link>
	<description>All things IT that I feel like sharing :)</description>
	<lastBuildDate>Thu, 23 Feb 2012 18:56:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='jrich523.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/24333509874ce512c176258db127b0f9?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>JRICH&#039;s Brain Dump</title>
		<link>http://jrich523.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://jrich523.wordpress.com/osd.xml" title="JRICH&#039;s Brain Dump" />
	<atom:link rel='hub' href='http://jrich523.wordpress.com/?pushpress=hub'/>
		<item>
		<title>PowerShell and Executables</title>
		<link>http://jrich523.wordpress.com/2012/02/23/powershell-and-executables/</link>
		<comments>http://jrich523.wordpress.com/2012/02/23/powershell-and-executables/#comments</comments>
		<pubDate>Thu, 23 Feb 2012 18:49:29 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[ampersand]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[executable]]></category>
		<category><![CDATA[invoke-command]]></category>
		<category><![CDATA[invoke-item]]></category>
		<category><![CDATA[invoked-expression]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[start-process]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=280</guid>
		<description><![CDATA[I don&#8217;t normally do posts like this, but I just created a Technet Wiki on PowerShell and executables. The only reason I created it there and didn&#8217;t do the post myself is that I think there is a lack of info on the topic and a community driven page might be of great help here. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=280&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t normally do posts like this, but I just created a Technet Wiki on PowerShell and executables. The only reason I created it there and didn&#8217;t do the post myself is that I think there is a lack of info on the topic and a community driven page might be of great help here. So, if you can, please populate it with more info!</p>
<p><a href="http://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx">http://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx</a></p>
<p>&nbsp;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/280/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/280/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/280/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/280/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/280/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/280/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/280/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/280/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=280&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2012/02/23/powershell-and-executables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShell: Getting Started with Win32 API</title>
		<link>http://jrich523.wordpress.com/2012/02/06/powershell-getting-started-with-win32-api/</link>
		<comments>http://jrich523.wordpress.com/2012/02/06/powershell-getting-started-with-win32-api/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 01:05:33 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[PInvoke]]></category>
		<category><![CDATA[Windows PowerShell]]></category>
		<category><![CDATA[win32_api]]></category>
		<category><![CDATA[win32]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=271</guid>
		<description><![CDATA[Blog on Request! Someone asked me to delve in to Win32 API use in PowerShell. Personally I don&#8217;t feel that I&#8217;m the best person to explain this, but I&#8217;ve done it a few times now so I think I have a decent handle on it. Let me just start off by saying Win32 API should be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=271&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Blog on Request!</p>
<p>Someone asked me to delve in to Win32 API use in PowerShell. Personally I don&#8217;t feel that I&#8217;m the best person to explain this, but I&#8217;ve done it a few times now so I think I have a decent handle on it.</p>
<p>Let me just start off by saying Win32 API should be your last choice (ok, second to last, I hate COM). You should do a very through search of the .NET framework before jumping in to the Win32 API pool.</p>
<p>Once you&#8217;ve exhausted all other options and have ended up in the Win32 world, what do you do? I&#8217;m not going to go over how to find the right WIN32 API for the task because if you are at this point, you&#8217;ve probably already found the API and just want to know how to use it.</p>
<p>First off load up the MSDN doc for it and the <a href="http://www.pinvoke.net/" target="_blank">PInvoke.net </a>doc. Usually googling the API will land you on those two pages pretty quickly.</p>
<p>Now for an example lets take a look at an API I&#8217;ve recently been playing with, <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa965224(v=vs.85).aspx" target="_blank">GetSystemFileCache</a> (<a href="http://www.pinvoke.net/default.aspx/kernel32/GetSystemFileCacheSize.html" target="_blank">pinvoke</a>)</p>
<p>The Signature that MSDN gives us looks like this.</p>
<p>BOOL WINAPI GetSystemFileCacheSize(   __out  PSIZE_T lpMinimumFileCacheSize,   __out  PSIZE_T lpMaximumFileCacheSize,   __out  PDWORD lpFlags );</p>
<p>Which is the signature you&#8217;d use if you were coding in C++.  Since there is no direct way to use this in PowerShell we&#8217;re going to embed this in C# code and then consume that code in PowerShell. In many cases I&#8217;ll write the C# console app first and then apply that to my PowerShell script. This is what I did with my <a title="NetStat for powershell!" href="http://jrich523.wordpress.com/2011/04/15/netstat-for-powershell/" target="_blank">NetStat</a> script, which was fairly complex. In this case we&#8217;re just calling a simple method to pull the current Cache limits.</p>
<p>Lets take a look at this Signature. The first thing shown is BOOL, which is the return type which the docs show is any nonzero number for success. Easy enough. bool is the same in C++ as it is in C#.</p>
<p>Next is WINAPI which is just a tag to show its a win32 api, this can just be removed.</p>
<p>After this is our method name, GetSystemFileCacheSize, easy enough.</p>
<p>Now this is where it gets a little tricky because we often times need to convert C++ types to something C# knows.</p>
<p>We see we have 3 arguments here, all 3 of which are prefixed with __out, which means they are output variables (If you don&#8217;t know how to program that well it&#8217;s basically passing a reference to a variable to return multiple things). So anytime you see __out, that means the variable needs to be passed in as a reference. We&#8217;ll get to that in a moment. Next is the type that the variable needs to be. Two of which are whats called PSIZE_T and one is a PDWORD. In both cases these are prefixed with a P, which indicates Pointer (pointer, reference, __out &#8211; all the same thing) so really the type is SIZE_T and DWORD.</p>
<p>How do we know what SIZE_T and DWORD are in C#? Google is really your best option here, or hopefully PInvoke.net has a signature you can use. In this case PInvoke does have it, but lets pretend it doesn&#8217;t. When we google &#8216;C# dword&#8217; we get some good results that let us know this is an unsigned Int (UInt32). Another clue we have is that in the MSDN docs it tells us that it&#8217;s a flag and it can have a value of 0&#215;1 or 0&#215;4, both of which fit in to an int just fine. So, which do we use? It doesn&#8217;t matter, provided all possible return types can fit in.</p>
<p>Next is that Size_T, again googling &#8216;C# SIZE_T&#8217; gives us some good info as does PInvoke, but lets just google SIZE_T.</p>
<p>Doing so provides a great <a href="http://msdn.microsoft.com/en-us/library/aa383751(v=VS.85).aspx#SIZE_T" target="_blank">data type reference</a>.</p>
<p>We can see that PSIZE_T is in there but it just says it&#8217;s a pointer to SIZE_T which we already knew.</p>
<p>&#8220;The maximum number of bytes to which a pointer can point. Use for a count that must span the full range of a pointer.</p>
<p>This type is declared in BaseTsd.h as follows:</p>
<p><code>typedef ULONG_PTR SIZE_T;</code>&#8220;</p>
<p>So this says it&#8217;s a ULONG (unsigned long, a long in C# is Int64, which google will help with again) It also indicates that it&#8217;s a pointer. This is where PInoke really saves us. It lets us know about an IntPtr type that is a special pointer specifically for this.</p>
<p>So now our new C# signature is as follows</p>
<p>bool GetSystemFileCacheSize(ref IntPtr lpMinimumFileCacheSize, ref IntPtr lpMaximumFileCacheSize, ref int lpFlags);</p>
<p>We see that it specifies ref for all the __out variables (in this case all of them, but some times they are __in) and a data type of IntPtr and int.</p>
<p>We&#8217;re still in the C# side of the world. we&#8217;ll need to use the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.aspx" target="_blank">System.Runtime.InteropServices </a>(otherwise known as pinvoke). If you don&#8217;t know C# this might be a bit tricky, but we&#8217;re going to write a small C# class to contain our method and create a wrapper function around it. Not always needed but I find it makes it easier to work with.</p>
<p><pre class="brush: plain;">

using System;

using System.Runtime.InteropServices;

public class test1

{

[DllImport(&quot;kernel32.dll&quot;)]

public static extern bool GetSystemFileCacheSize(ref IntPtr lpMinimumFileCacheSize, ref IntPtr lpMaximumFileCacheSize, ref int lpFlags);

public struct CacheSize

{

public Int64 Min;

public Int64 Max;

public int Flags;

}

public static CacheSize GetSize()

{

IntPtr lpMin = IntPtr.Zero;

IntPtr lpMax = IntPtr.Zero;

int lpFlags = 0;

bool b = GetSystemFileCacheSize(ref lpMin, ref lpMax, ref lpFlags);

CacheSize size = new CacheSize();

size.Min = lpMin.ToInt64();

size.Max = lpMax.ToInt64();

size.Flags = lpFlags;

return size;

}

</pre></p>
<p>The first part of this is just adding the pinvoke namespace and the basic system namespace which helps with the IntPtr. We then create a public class. I usually start with Test1 because once you add a type to PowerShell you can&#8217;t overwrite it.</p>
<p>Then you&#8217;ll see the keywords [DLLImport("kernel32.dll")] so depending on what DLL your function is in will determin what you put in there which is followed by the signature.</p>
<p>Next I created a struct to help with the output to PowerShell. You&#8217;ll see how this comes in to play as we start to work with the PowerShell side of things. For now just see that it&#8217;s a simple holder for our return data. Next is our function wrapper. I&#8217;ve called it GetSize which returns my struct. You&#8217;ll also notice that it&#8217;s prefiexed with <em>public static </em>for both, which is important for accessing it within PowerShell.</p>
<p>In my function I set my min and max pointer to zero (special pointer zero) and the flags to zero. I then call the win32 api passing it the variables I created as references (pointers) and capture the return in b which if I was trying to do something for production, I&#8217;d check the return value.</p>
<p>I then create an object of my type CacheSize and populate it with the return values and return that to the caller.</p>
<p>Now that the C# is done, how do we apply this in PowerShell?</p>
<p>If you read my blog you&#8217;ll notice I&#8217;ve used Add-Type a few times which is a great tool for adding in types or C# code as we are doing here so we&#8217;ll just wrap this in a here-string and pass it to Add-Type like so:</p>
<p><pre class="brush: powershell;">

Add-Type

&lt;span style=&quot;color: #8b0000; font-family: Lucida Console; font-size: xx-small;&quot;&gt;&lt;span style=&quot;color: #8b0000; font-family: Lucida Console; font-size: xx-small;&quot;&gt;&lt;span style=&quot;color: #8b0000; font-family: Lucida Console; font-size: xx-small;&quot;&gt;@'&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;

using System;

using System.Runtime.InteropServices;

public class test1

{

[DllImport(&quot;kernel32.dll&quot;)]

public static extern bool GetSystemFileCacheSize(ref IntPtr lpMinimumFileCacheSize, ref IntPtr lpMaximumFileCacheSize, ref int lpFlags);

public struct CacheSize

{

public Int64 Min;

public Int64 Max;

public int Flags;

}

public static CacheSize GetSize()

{

IntPtr lpMin = IntPtr.Zero;

IntPtr lpMax = IntPtr.Zero;

int lpFlags = 0;

bool b = GetSystemFileCacheSize(ref lpMin, ref lpMax, ref lpFlags);

CacheSize size = new CacheSize();

size.Min = lpMin.ToInt64();

size.Max = lpMax.ToInt64();

size.Flags = lpFlags;

return size;

}

}

'@

</pre></p>
<p>NOTE: Be careful of new lines in this code, the code formatter has been doing weird things to me lately.</p>
<p>Once you run that its imported the class in to our running environment and we can access that method like so.</p>
<p><pre class="brush: powershell;">

$rtn = [test1]::getsize()

$rtn

$rtn | select @{n='min';e={$_.min /1mb}}, @{n='Max';e={$_.max/1gb}},flags

</pre></p>
<p>The return should be the same on all systems (at least what I&#8217;ve seen from tests) as 1MB min and 1024GB max. If you have a file server that&#8217;s hosting TB&#8217;s of data, you might find this to be a problem when its eaten all of your memory in system cache!</p>
<p>There is a way to set it with a win32 API that im working on now. I&#8217;ll be sure to post that solution when I figure it out!</p>
<p>I hope this has helped you understand how to use Win32 APIs a little better!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/271/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=271&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2012/02/06/powershell-getting-started-with-win32-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShell: Custom Objects with Format Files</title>
		<link>http://jrich523.wordpress.com/2012/01/20/powershell-custom-objects-with-format-files/</link>
		<comments>http://jrich523.wordpress.com/2012/01/20/powershell-custom-objects-with-format-files/#comments</comments>
		<pubDate>Fri, 20 Jan 2012 17:17:37 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[custom object]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[format file]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[Windows PowerShell]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=258</guid>
		<description><![CDATA[I was recently working on something and realized that the default output (everything) was getting rather annoying. I then realized that the object I had wasnt going to cut it and I had to create my own. This led to two problems: 1. I needed to get formatting for my data and since&#160;I was going [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=258&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was recently working on something and realized that the default output (everything) was getting rather annoying. I then realized that the object I had wasnt going to cut it and I had to create my own. This led to two problems:</p>
<p>1. I needed to get formatting for my data and since&nbsp;I was going to post the script online I didn&#8217;t&nbsp;want to make it a multi file solution. I wanted it so&nbsp;the end-user could just copy and paste the entire thing in to one file and run it.</p>
<p>2. In knowing that I needed custom formating I realized the normal PSObject wasnt going to cut it.</p>
<h2>Step 1 (Item 2) The Custom Object</h2>
<p>This part isn&#8217;t really all that hard, but its something I thought I would show. If you know C# this will make perfect sense, if you don&#8217;t, it will likely still make perfect sense. In order to have a type name with our object we have to define it via&nbsp;a C# class (Other .NET languages work, but I know and like C#.) You can make this as simple or as complex as you like but for this example its going to be very simple. We&#8217;re going to make a Contact object.</p>
<p><pre class="brush: powershell;">
add-type @'
namespace JRICH
{
    public class Contact
    {
public string FName;
public string LName;
public string DisplayName()
        {
return (this.FName + &quot; &quot; + this.LName);
        }
    }
}
'@
</pre></p>
<p>There are a couple of&nbsp;note worthy items here. First you&#8217;ll see I&#8217;ve provided a namespace for this class. This isn&#8217;t&nbsp;needed but I find it to be good practice to help prevent duplication of class names. Also you&#8217;ll want to be weary of case in the C# side of things because it is case-sensitive. Along those lines you&#8217;ll notice that each line ends in a ;. As I said if you know C# this is no big deal, but if you are a scripter/admin learning PowerShell these are important notes.</p>
<p>One other thing I&#8217;ll say here is that if you are not used to C# and you plan on doing this you might want to grab a copy of <a href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express">Visual C#&nbsp;Express</a>&nbsp;which you can download for&nbsp;free. The debugging and Intellisense will really help with learning C#.</p>
<p>Another reason to use Visual C# is that when creating a class in PowerShell once you add the type there is no way to remove it or overwrite it so after you add the type and decide you want to change it, you&#8217;ll need to close PowerShell and open it again.</p>
<p>In this case I&#8217;ve created a class called Contact which has a first name, last name and a display name method to give a friendly view of this.</p>
<p>Now that we have this custom object lets use it.</p>
<p>
$contact = new-object jrich.contact
$contact.fname = &quot;Justin&quot;
$contact.lname = &quot;Rich&quot;
$contact
#FName            LName
#-----------------------
#Justin           Rich
$contact.displayname()
#Justin Rich
</p>
<p>Pretty easy huh?</p>
<p>Now that we have an object to work with&nbsp;lets put it in a script.&nbsp;Lets make a function&nbsp;that returns a handful of users. I&#8217;m making this overly simple but I think&nbsp;you&#8217;ll see how to apply this in your own scripts.</p>
<p><pre class="brush: powershell;">
function Get-MyUsers ([string[]] $User)
{
    Begin
    {
        $results = @()
    }
    Process
    {
foreach($usr in $user)
        {
$tmp = new-object jrich.contact
$tmp.lname, $tmp.fname = $usr.split(',')
$results += $tmp
        }
    }
    End
    {
        $results
    }
}
Get-MyUsers @(&quot;rich,justin&quot;,&quot;smith,john&quot;,&quot;doe,jane&quot;)
</pre></p>
<p><strong>Shortcut:</strong>&nbsp;Ctrl+J will bring up the snippet menu (in ISE) which will allow you to generate a function body very quickly.</p>
<h2>Step 2 (Item 1) The Format File</h2>
<p>Our simple function is all well and good but lets say we are unhappy with the default output format and want to change it so the user doesn&#8217;t have to do it every time. In order to change the default display we need a Format File. The Help system has <a href="http://technet.microsoft.com/en-us/library/dd315396.aspx">About_format.ps1xml </a>and <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/gg580944(v=vs.85).aspx">MSDN</a>&nbsp;has pretty detailed documents on it, but lets just say its fairly complex. Thankfully James Brundage over at<a href="http://start-automating.com/"> Start-Automating.com </a>has created <a href="http://ezout.start-automating.com/">EZOUT</a>,&nbsp;a very nice tool to help us create those format files.</p>
<p>Im not going to go in to details on how to create these files or use that tool since there is a very nice YouTube video for it.</p>
<p>Back to our function. Lets say we&#8217;d like to make the default view be the return of the Displayname method.</p>
<p>This is the XML that the EZOUT has spit out for us.</p>
<p><pre class="brush: xml;">
xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;
&lt;Configuration&gt;&lt;ViewDefinitions&gt;&lt;View&gt;
    &lt;Name&gt;jrich.contact&lt;/Name&gt;
    &lt;ViewSelectedBy&gt;
        &lt;TypeName&gt;jrich.contact&lt;/TypeName&gt;
    &lt;/ViewSelectedBy&gt;
    &lt;TableControl&gt;
        &lt;TableHeaders&gt;
            &lt;TableColumnHeader&gt;&lt;Label&gt;DisplayName&lt;/Label&gt;&lt;/TableColumnHeader&gt;
        &lt;/TableHeaders&gt;
        &lt;TableRowEntries&gt;
            &lt;TableRowEntry&gt;
                &lt;TableColumnItems&gt;
$_.displayname()
                &lt;/TableColumnItems&gt;
            &lt;/TableRowEntry&gt;
        &lt;/TableRowEntries&gt;
    &lt;/TableControl&gt;
&lt;/View&gt;&lt;/ViewDefinitions&gt;&lt;/Configuration&gt;
</pre></p>
<p>Typically what you would do is save this file and use the Update-FormatData&nbsp;cmdlet to import this in to PowerShell&#8217;s current session environment.</p>
<p>In our case, because we don&#8217;t&nbsp;want to have more than&nbsp;one file we want to embed this in to our script. Since the only way to get this format data in to the environment&nbsp;is to use the Update-FormatData we&#8217;ll need to write this out to a file so we&#8217;ll inject this in to our Begin script block along with our class definition to make this a stand alone script.</p>
<p><pre class="brush: powershell;">
function Get-MyUsers ([string[]] $User)
{
    Begin
    {
        try{
            add-type @'
namespace JRICH
{
    public class Contact
    {
public string FName;
public string LName;
public string DisplayName()
        {
            return (this.FName + &quot; &quot; + this.LName);
        }
    }
}
'@
            }
        catch{}

$formatfile = &quot;$pshome\jrich.contact.format.ps1xml&quot;
$typedata = @'
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;
&lt;Configuration&gt;&lt;ViewDefinitions&gt;&lt;View&gt;
    &lt;Name&gt;jrich.contact&lt;/Name&gt;
    &lt;ViewSelectedBy&gt;
        &lt;TypeName&gt;jrich.contact&lt;/TypeName&gt;
    &lt;/ViewSelectedBy&gt;
    &lt;TableControl&gt;
        &lt;TableHeaders&gt;
            &lt;TableColumnHeader&gt;&lt;Label&gt;DisplayName&lt;/Label&gt;&lt;/TableColumnHeader&gt;
        &lt;/TableHeaders&gt;
        &lt;TableRowEntries&gt;
            &lt;TableRowEntry&gt;
                &lt;TableColumnItems&gt;
                    &lt;TableColumnItem&gt;&lt;ScriptBlock&gt;$_.displayname()&lt;/ScriptBlock&gt;&lt;/TableColumnItem&gt;
                &lt;/TableColumnItems&gt;
            &lt;/TableRowEntry&gt;
        &lt;/TableRowEntries&gt;
    &lt;/TableControl&gt;
&lt;/View&gt;&lt;/ViewDefinitions&gt;&lt;/Configuration
'@

if(!(Test-Path $formatfile))
        {
$typedata | out-file $formatfile
        }
        Update-FormatData -AppendPath $formatfile
        $results = @()
    }
    Process
    {
foreach($usr in $user)
        {
            $tmp = new-object jrich.contact
            $tmp.lname, $tmp.fname = $usr.split(',')
$results += $tmp
        }
    }
    End
    {
        $results
    }
}

</pre></p>
<p>There are a couple of things to note here. First is that we&#8217;ve enclosed our type definition in a Try/Catch statement. The reason for this is that once we load our type in to the environment we cant do it again as we saw with creating it and trying to update it.</p>
<p>The next thing is the actual&nbsp;process of adding in the formating data. You&#8217;ll notice&nbsp;I&nbsp;define a file based on the $PSHome&nbsp;variable (PowerShell install location) and tacked on a file name. To make sure it&#8217;s never overwritten I&#8217;ve named it based on the namespace and class. We then define the XML as a string and check to see if that file is there and if not write the file and update the format data.</p>
<p>One thing to note is that this method should only be used when you want to make a single script file to be distributed. If you are making a module the process of format files is a bit different. Want to know about that? Comment on this post and I&#8217;ll do a write-up on it.</p>
<p>Hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/258/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/258/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/258/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/258/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/258/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/258/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/258/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/258/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=258&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2012/01/20/powershell-custom-objects-with-format-files/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>Managing Remote (WSMAN) sessions with PowerShell</title>
		<link>http://jrich523.wordpress.com/2012/01/19/managing-remote-wsman-sessions-with-powershell/</link>
		<comments>http://jrich523.wordpress.com/2012/01/19/managing-remote-wsman-sessions-with-powershell/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 16:06:10 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[enter-pession]]></category>
		<category><![CDATA[get]]></category>
		<category><![CDATA[get-session]]></category>
		<category><![CDATA[instance]]></category>
		<category><![CDATA[new-pssession]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[remove]]></category>
		<category><![CDATA[remove-pssession]]></category>
		<category><![CDATA[remove-session]]></category>
		<category><![CDATA[sessions]]></category>
		<category><![CDATA[Windows PowerShell]]></category>
		<category><![CDATA[wsman]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=249</guid>
		<description><![CDATA[There was a post on the forums asking about how to remove a session if the max sessions (5) had been reached. You could use Get-Process to find and kill a WsmProvHost but killing things is never a good idea. There is a Get-WSManInstance but it&#8217;s not very friendly so I&#8217;ve wrapped that and Remove-WSManInstance in to two functions [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=249&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There was a post on the forums asking about how to remove a session if the max sessions (5) had been reached. You could use Get-Process to find and kill a WsmProvHost but killing things is never a good idea. There is a Get-WSManInstance but it&#8217;s not very friendly so I&#8217;ve wrapped that and Remove-WSManInstance in to two functions that are much more user-friendly. Just copy and past this in to a file and you can use Import-Modulein your profile to add these functions in to your environment.</p>
<p><pre class="brush: powershell;">
&lt;#
.Synopsis
Display WSMan Connection Info
.DESCRIPTION
This is a wrapper to Get-WSManInstance
.EXAMPLE
Get-RemotePSSession ServerABC
.EXAMPLE
$s = Get-RemotePSSession ServerABC
$s | Remove-RemotePSSession
#&gt;
function Get-RemotePSSession
{
[CmdletBinding()]
    Param
    (
        # Computer to query.
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   Position=0)]
        [string]
$ComputerName,

# use SSL
        [switch]
$UseSSL
    )

    Begin
    {
        try{
            Add-Type  @&quot;
namespace JRICH{
public class PSSessionInfo
            {
                public string Owner;
public string ClientIP;
public string SessionTime;
public string IdleTime;
public string ShellID;
public string ConnectionURI;
public bool UseSSL=false;
            }}
&quot;@
        }
        catch{}
        $results = @()

    }
    Process
    {

$port = if($usessl){5986}else{5985}
$URI = &quot;http://$($computername):$port/wsman&quot;
$sessions = Get-WSManInstance -ConnectionURI $URI shell -Enumerate

foreach($session in $sessions)
        {
            $obj = New-Object jrich.pssessioninfo
            $obj.owner = $session.owner
            $obj.clientip = $session.clientIp
$obj.sessiontime = [System.Xml.XmlConvert]::ToTimeSpan($session.shellRunTime).tostring()
$obj.idletime = [System.Xml.XmlConvert]::ToTimeSpan($session.shellInactivity).tostring()
            $obj.shellid = $session.shellid
            $obj.connectionuri = $uri
            $obj.UseSSL = $usessl
            $results += $obj
        }
    }
    End
    {
        $results
    }
}

&lt;#
.Synopsis
Logoff remote WSMAN session
.DESCRIPTION
   This function will take a JRICH.PSSessionInfo object and disconnect it
.EXAMPLE
$s = Get-RemotePSSession ServerABC
$s | Remove-RemotePSSession
#&gt;
function Remove-RemotePSSession
{
[CmdletBinding()]
    Param
    (
        # Session to be removed.
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   Position=0)]
        [jrich.pssessioninfo[]]
        $Session

    )

    Process
    {
foreach($connection in $session)
        {
Remove-WSManInstance -ConnectionURI $connection.connectionuri shell @{ShellID=$connection.shellid}
        }
    }

}
</pre><br />
Edit: Thanks Alex for catching the use of &#8220;CredSSP&#8221; vs &#8220;UseSSL&#8221; which is the common arg on PSSession cmdlets!</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/249/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/249/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/249/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=249&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2012/01/19/managing-remote-wsman-sessions-with-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShell &#8211; The Trouble With All That Power</title>
		<link>http://jrich523.wordpress.com/2012/01/05/powershell-the-trouble-with-all-that-power/</link>
		<comments>http://jrich523.wordpress.com/2012/01/05/powershell-the-trouble-with-all-that-power/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 23:44:12 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[best practice]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Windows PowerShell]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=219</guid>
		<description><![CDATA[Lately I&#8217;ve seen a lot more conversations on the forums about how much error checking you should do, how careful you should be, should you include aliases in your modules. Silly questions you may say. This comes down to two problems. The Problems The Admin Think of this, PowerShell is the only language that has [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=219&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve seen a lot more conversations on the forums about how much error checking you should do, how careful you should be, should you include aliases in your modules. Silly questions you may say.</p>
<p>This comes down to two problems.</p>
<h2>The Problems</h2>
<h3>The Admin</h3>
<p>Think of this, PowerShell is the only language that has an interactive environment that allows you to deal with objects. Ok so there might be some others out there, but they aren&#8217;t as popular (and I don&#8217;t use them!). Whats the big deal you ask? If you are at all like me you leave your console (ISE for me) open all the time and by all the time I mean it loads when the system is booted and stays open (my system is only rebooted for patches). I don&#8217;t have a good reason other than I like PowerShell at my finger tips. Still with me? Now chances are if you do this you also tend to work in PowerShell and store data here and there to variables to quickly test or work with something and lets say its a server you&#8217;re working with, do you do this too?</p>
<p><pre class="brush: powershell;">

$s = &quot;MyServer&quot;

gwmi win32_Computersystem -co $s

gwmi win32_share -co $s

</pre></p>
<p>Whats wrong with this? I stored my server name in $s which is certainly easy for me to type as I work on the fly. Problem is, a few hours later when I start to do something different I reuse that $s for another server, or perhaps something else. It&#8217;s just a server name, no big deal right? What about $dt to store a datetime object? I do that a lot, or $dt to store a data table. Perhaps you see where this is going. As this shell stays open for multiple days I might overwrite a variable and then when I want to look at it again  I have a problem (that datatable with all the SQL data now contains a date, opps.) This is obviously a user error and I&#8217;ve trained myself to open tabs to deal with problems like this (I really don&#8217;t want to type long variable names)</p>
<p>Problem solved!</p>
<p>No, the problem is that more and more people are developing some really neat modules. I personally try to stay away from them because I tend to take what I do on the fly and turn it in to a script that will be run from a server, and I&#8217;m not going to install modules there. Even with that said I find that my module collection is growing.</p>
<p>Where am I going with this? As you install more modules, and create your own and start working more and more in PowerShell you&#8217;re likely to run in to the problem of variable/alias confusion. Even though its a &#8217;Best Practice&#8217; to label your functions with meaningful names (good job Quest: Get-QADUser)  you don&#8217;t always see that in practice. On the plus side MS is cutting this off with the new Intillisense that PS3 has which will ask which one you want to use. But still, as the years go by and more and more cool stuff comes out this will start to be a rather large problem. This isn&#8217;t something that we needed to deal with back in the day, once you ran the script, all of those variables were gone upon completion. If you worked in *nix, you likely didn&#8217;t use the shell like that (plus its all text and not objects, no fun.)</p>
<p>On top of this, more modules are creating variables. Most of them are fairly verbose with their names, but not all. I often find myself trying to use $host to store a hostname. As the PowerShell environment grows we&#8217;ll need to be more and more careful about what variables we use.</p>
<p>Advice?  First read on.</p>
<h3>The Developer</h3>
<p>The developer problem isn&#8217;t a new one, but it&#8217;s probably new to a lot of you PowerShell guys who are admins and want to use PowerShell to automate things and like the interactive console idea. My background is a mix bag of admin and development. My admin experience is much stronger, but I know enough in both areas to understand this problem.</p>
<p>As you write code you&#8217;re first goal is to make it do what you want it to do, which is the fun part. Once you get the code working the way you want, you should ask yourself, what could break this and how can I stop/trap it?</p>
<p>If you spend any deal of time on this you are likely to become overwhelmed with just how many things can break your code. I once heard of the 80/20 rule (there are many versions) for programming.</p>
<p>20% logic (the work) and 80% error checking. If you think that&#8217;s a lot, think of this. Lets say you want to modify a file on a remote system you&#8217;ll first want to verify that the system is online with a test-connection because its quick. Then you&#8217;ll want to make sure you can access the file location (timeout is generally slower for this) and then you want to check if the file is there and if it is you want to make sure you can edit it.</p>
<p>There are two methods of thought, test first, or trap errors. I wont say one method is better than the other, I use both depending on whats faster/safer.</p>
<p>Where am I going with this?</p>
<h2>To the Point - The Knowledge:</h2>
<p>The problem I see is that people do one of two things, they over think it and get overwhelmed with how many things can go wrong, or they just say it works, I&#8217;m done!</p>
<p>There is some great documents out there on this, but this isn&#8217;t a programming class, it&#8217;s an adaptation for the admin who wants to write code. It comes down to two main things:</p>
<p><strong>Know The Audience</strong> &#8211; I think this is a big one, who will use this code? What is their ability level? Is it a helpdesk team that wont be able to figure out what the PowerShell error means or is it technical group?  Is it to be deployed as a server job? Is it being sold or published to the community?</p>
<p><strong>Know The Risk</strong> - What is the repercussion of this script failing? If it&#8217;s a server job it could be really bad. You might lose data over it. If it&#8217;s for a client you run the risk of making them unhappy and increase support costs. If it&#8217;s for the community then the project could fail. If it&#8217;s for you, well, you probably don&#8217;t care.</p>
<p>My point here is that there is a middle ground on how much error checking needs to be done. Most aren&#8217;t doing enough, and some are over thinking it. So the next time you write a script and think you are down with it, think about your audience and what will happen if this script fails.</p>
<p><a href="http://salimsribasuki.files.wordpress.com/2010/03/software-design-at-its-finest.jpg"><img class="alignnone" title="Software Design" src="http://salimsribasuki.files.wordpress.com/2010/03/software-design-at-its-finest.jpg?w=448&#038;h=336" alt="" width="448" height="336" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/219/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=219&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2012/01/05/powershell-the-trouble-with-all-that-power/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>

		<media:content url="http://salimsribasuki.files.wordpress.com/2010/03/software-design-at-its-finest.jpg" medium="image">
			<media:title type="html">Software Design</media:title>
		</media:content>
	</item>
		<item>
		<title>Powershell: Working with strings &#8211; Data Manipulation</title>
		<link>http://jrich523.wordpress.com/2011/12/21/powershell-working-with-strings-data-manipulation/</link>
		<comments>http://jrich523.wordpress.com/2011/12/21/powershell-working-with-strings-data-manipulation/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 17:53:34 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[data manipulation]]></category>
		<category><![CDATA[hello world]]></category>
		<category><![CDATA[string data]]></category>
		<category><![CDATA[string object]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=94</guid>
		<description><![CDATA[In my frist post, PowerShell: Working with Strings I talked about the types of strings and how to make them. Now lets talk about how to manipulate that data. What it comes down to is one of two types of string data. It&#8217;s either a single string, or a collection of strings. Get-Content returns a collection [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=94&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my frist post, <a href="http://jrich523.wordpress.com/2011/07/01/powershell-working-with-strings/">PowerShell: Working with Strings</a> I talked about the types of strings and how to make them. Now lets talk about how to manipulate that data.</p>
<p>What it comes down to is one of two types of string data. It&#8217;s either a single string, or a collection of strings. Get-Content returns a collection of strings as do many other cmdlets and most cmd programs (ipconfig)  so we are going to work with these two sets.</p>
<p><pre class="brush: powershell;">

$str1 = &quot;hello world!&quot;

$str2 = &quot;hello&quot;,&quot;world&quot;

</pre></p>
<p>The $str2 is just a way to simulate what Get-Content would give us.</p>
<p>First, lets start by looking to see what we can do with a basic string:</p>
<p><pre class="brush: powershell;">

$str1 | gm

</pre></p>
<p>You&#8217;ll notice you have a <a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">System.String object</a> and a bunch of methods to work with. One thing to keep in mind about a String is that its <a href="http://en.wikipedia.org/wiki/Immutable_object">immutable</a> which basically means you can&#8217;t change the value of the variable, you&#8217;ll need to store it to a new variable with the new value you want. Lets try to change our basic string to upper case:</p>
<p><pre class="brush: powershell;">

$str1.ToUpper()

$str1

</pre></p>
<p>You&#8217;ll notice when we just type $str1 its back to lower case (ie, immutable).  So if we wanted to keep that we&#8217;d need to store it some place, but lets keep it as it is.</p>
<p>Looking at my original string you&#8217;ll see its all lower case, so lets change that h to an H. There are a few ways we can do it, and since we only have one H in this string, we have even more options. Most of these are a bit over kill, but they allow me to show an assortment of methods.</p>
<p><pre class="brush: powershell;">

#simple replace

$str1.replace(&quot;h&quot;,&quot;H&quot;)

#sub string grabs from index to end in this case

#we just slap an H in front, good if there are multiple h's

&quot;H&quot; + $str1.substring(1)

&quot;H$($str1.substring(1))&quot;

#now in to the over kill

$str1.Insert(0,&quot;H&quot;).Remove(1,1)

$str1.Remove($str1.IndexOf(&quot;h&quot;),1).Insert(0,&quot;h&quot;)

</pre></p>
<p>There are a few neat things to note here, the first being tacking on to methods.</p>
<p>$object.method().method().method() and so on</p>
<p>Which would work something like this</p>
<p>(($object.method()).method()).method()</p>
<p>Too many parentheses to follow? The point is, as you tack them on the new method works on the result of the previous, in our case it&#8217;s always a string, but that could change depending on what you are doing.</p>
<p>Another thing is the nesting of methods which can be handy, but some times harder to follow, in a script, it usually worth while to add a few extra characters to make it readable.</p>
<p>As you noticed when you did the Get-Member (shorthand gm) on the string, there were a lot of methods and it had the definition for each but most were packed in and it was hard to read, so if you are curious you can go to <a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">MSDN </a>or you can type a method in without the () like so:</p>
<p><pre class="brush: powershell;">

$str1.substring

</pre></p>
<p>Doing so will spit out something like this:</p>
<p>OverloadDefinitions</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>string Substring(int startIndex)</p>
<p>string Substring(int startIndex, int length)</p>
<p>Which shows the different ways to call the method. The first item is the return type, in both cases here it&#8217;s a string. Then it shows the name of the method and its param options. We have two cases here, a StartIndex and a StartIndex and Length. In the first case we provided a starting point and it goes to the end of the string, in the next case we provide a starting point and a distance.</p>
<p><pre class="brush: powershell;">

$str1.substring(6)

$str1.substring(6,5)

[sourcecode]

So far everything we've been doing is .NET methods from the String object but PowerShell has some neat ways to handle this as well.

[sourcecode langauge='powershell']

$str1 -replace &quot;h&quot;, &quot;H&quot;

</pre></p>
<p>This works just as well but there a two very important notes here the first being that the .NET methods are case-sensitive and PowerShell is not, try this:</p>
<p><pre class="brush: powershell;">

$str1 -replace &quot;E&quot;, &quot;h&quot;

$str1.replace(&quot;E&quot;,&quot;h&quot;)

</pre></p>
<p>In the first case the e was replaced and in the second it was not.</p>
<p>The other thing to keep in mind is that many of the <a href="http://technet.microsoft.com/en-us/library/dd315321.aspx">PowerShell comparison operators</a> use regular expressions rather than just simple character replacement as the .NET methods do. I&#8217;ll go in to RegEx and the different operators in my next post on strings.</p>
<p>Now, I mentioned two types of string data and really only talked about one. The reason I made mention of both is so that you don&#8217;t try to do these operations on the return of a get-content or on the output of a command app.</p>
<p>One Thing I would like to point out is the Length property on our objects $str1 and $str2.</p>
<p><pre class="brush: powershell;">

$str1.length

$str2.lenght

$str2[0].length

</pre></p>
<p>You&#8217;ll notice that the return on $str2.lenth is 2, which is how many items are in the array. This may seem obvious now, but when working with PowerShell you may not always know ahead of time if it&#8217;s an array or not (Another post on arrays some day.)</p>
<p>If however you have data like that and would like to make it a single string, you can do so with Join. Again you have the .NET and PowerShell way to do this.</p>
<p><pre class="brush: powershell;">

$str2 -join &quot; &quot;

[string]::join(&quot; &quot;,$str2)

</pre></p>
<p>You&#8217;re probably wondering where the [string]::join came from. That&#8217;s a static method on the String class that was not listed by the gm we did before. If you looked at the MSDN docs you&#8217;ll see some methods with an S next to them, indicating they are static, but, who wants to leave PowerShell?</p>
<p><pre class="brush: powershell;">

gm -i $str1 &lt;strong&gt;-Static&lt;/strong&gt;

</pre></p>
<p>Thankfully the Get-Member cmdlet has a Static param that will show us the static methods available to an object of that type! Have I mentioned before how much I love <a href="http://jrich523.wordpress.com/2011/06/20/get-member-powershells-most-powerfull-cmdlet/">Get-Member</a>?</p>
<p>There is a ton more that can be done with strings but, I hope this enough to allow you to dig in to it more on your own!</p>
<p>Until next time (RegEx!)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/94/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/94/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/94/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=94&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2011/12/21/powershell-working-with-strings-data-manipulation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating DataStores From EMC Storage for your VMWare ESX environment with PowerCLI</title>
		<link>http://jrich523.wordpress.com/2011/12/16/creating-datastores-from-emc-storage-for-your-vmware-esx-environment-with-powercli/</link>
		<comments>http://jrich523.wordpress.com/2011/12/16/creating-datastores-from-emc-storage-for-your-vmware-esx-environment-with-powercli/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 19:39:32 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[EMC (CX VNX)]]></category>
		<category><![CDATA[VMWare]]></category>
		<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[datastore]]></category>
		<category><![CDATA[esx]]></category>
		<category><![CDATA[lun]]></category>
		<category><![CDATA[powercli]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[vmware]]></category>
		<category><![CDATA[VNX]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=193</guid>
		<description><![CDATA[I recently built my VMWare ESX environment out and we&#8217;ve got a VNX 5700 for our SAN. At some point we&#8217;ll be implimenting Site Recovery Manager and it was recommended that we use 1TB LUNs which is fine, but I&#8217;ve ended up with a lot of LUNs to map. Doing this in the client would [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=193&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently built my VMWare ESX environment out and we&#8217;ve got a VNX 5700 for our SAN. At some point we&#8217;ll be implimenting Site Recovery Manager and it was recommended that we use 1TB LUNs which is fine, but I&#8217;ve ended up with a lot of LUNs to map. Doing this in the client would just suck and the CLI is ok, but its a lot of tracking down to give them meaningful names.</p>
<p>How I prefer to name my DataStores is to use something that lets me know where it lives, like this VNX_P100_L15. This indicates the storage array (only have one VNX) and then the Pool that the LUN lives in (to indicate its performance level) and then the LUN number.</p>
<p>If you were to try and do this by hand its rather painful, so I wrote a script to do this for me.</p>
<p><strong>Things you&#8217;ll need:</strong></p>
<ul>
<li>NaviSecCLI in your system path and security configured (would be easy to add perms to this if needed).</li>
<li>PowerCLI installed and connected (Connect-VIServer).</li>
<li>The IP of an SP on your VNX (any EMC array should work here).</li>
<li>The Storage Group you use for your VNX.</li>
<li>The Storage accessible to your environment (Get-VMHost | Get-VMHostStorage -RescanAllHba -RescanVmfs will make sure all hosts see the storage)</li>
</ul>
<p><pre class="brush: powershell;">
## EMC info
$sg = &quot;&lt;your Storage Group Name, Case matters&quot;
$ip = &quot;IP of an SP&quot;
## VM info
$vmhost = Get-VMHost &quot;Any ESX Hostname&quot; ##any host since all should see storage

###EMC data gathering
## get ALU/HLU
$rtn = (naviseccli -h $ip storagegroup -list -gname $sg) -match &quot;\s+\d+\s+\d+&quot;

$luns = @()
$rtn | %{$luns += ,(-split $_)}

##[0] = host(HLU), [1] = storage(ALU)

##Find what pool the LUN belongs to.
for($i=0;$i -lt $luns.count; $i++)
{
    $pool = ((naviseccli -h $ip lun -list -l $luns[$i][1]) -match &quot;pool name&quot;)[0].substring(10).trim()
    ## in my case remove &quot;pool&quot; in pool names are something like &quot;Pool 100&quot;, you're might be different
    $pool = $pool.replace(&quot;Pool &quot;,&quot;&quot;)

    ##Build Lun Names
    $luns[$i] += &quot;VNX_P$($pool)_L$($luns[$i][1])&quot;
}

## VNX part
##get host lun numbers with the lun itself.
$VMLUNS = $VMHost | Get-SCSILun |?{$_.vendor -eq &quot;DGC&quot; -and $_.capacitymb  -gt 1024} | select *,HOSTLUN
$VMLUNKey = (get-view $vmhost).Config.StorageDevice.ScsiTopology | ForEach {$_.Adapter} | ForEach {$_.Target} | ForEach {$_.Lun}
$VMLUNS | %{$key = $_.key; $_.HOSTLUN = $VMLUNKey |?{$_.scsilun -eq $key} | select -exp lun -un}

##currently used canonicals to make sure you dont try to create a used datastore
$inuse = Get-Datastore | where {$_.type -eq 'vmfs'} | get-view | %{$_.info.vmfs.extent} | select -ExpandProperty diskname
$vmluns = $VMLUNS | ? {$inuse -notcontains $_.canonicalname}

##Create the DataStores
foreach($vmlun in $vmluns)
{
    $hostlun = $vmlun.HOSTLUN
    $lun = $luns | where { $_[0] -eq $hostlun}

    New-Datastore -VMHost $vmhost -Name $($lun[2]) -Path $($vmlun.canonicalname) -BlockSizeMB 2 -Vmfs
}

## rescan so all hosts see new DataStores
Get-VMHost | Get-VMHostStorage -RescanAllHba -RescanVmfs
</pre></p>
<p>You&#8217;ll notice I set the BlockSizeMB to be 2, which limits VM disk to 512GB, which is generally enough (good middle ground for SRM)</p>
<p>Im new to ESX so any feedback would be welcomed.</p>
<p>Hope it helps!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/193/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/193/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/193/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/193/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/193/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/193/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/193/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/193/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=193&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2011/12/16/creating-datastores-from-emc-storage-for-your-vmware-esx-environment-with-powercli/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>Using WMI to link a Disk Volume to a Physical Disk with PowerShell</title>
		<link>http://jrich523.wordpress.com/2011/12/12/using-wmi-to-link-a-disk-volume-to-a-physical-disk-with-powershell/</link>
		<comments>http://jrich523.wordpress.com/2011/12/12/using-wmi-to-link-a-disk-volume-to-a-physical-disk-with-powershell/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 19:27:04 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[win32_diskdrive]]></category>
		<category><![CDATA[win32_volume]]></category>
		<category><![CDATA[wmi]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=185</guid>
		<description><![CDATA[Recently someone asked how to map a disk volume to a physical disk. At first I figured this would be real easy and just involve two WMI calls. Come to find out, it&#8217;s not that easy, but not impossible. Not too bad, but could be better. There is a GetRelated method that PowerShell tack on to WMI objects which should [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=185&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently someone asked how to map a disk volume to a physical disk. At first I figured this would be real easy and just involve two WMI calls. Come to find out, it&#8217;s not that easy, but not impossible.</p>
<p><pre class="brush: powershell;">

$diskdrive = gwmi win32_diskdrive

foreach($drive in $diskdrive)

{

out-host -InputObject &quot;`nDrive: deviceid-$($drive.deviceid.substring(4)) Model - $($drive.model)&quot;

##partition

$partitions = gwmi -Query &quot;ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`&quot;$($drive.DeviceID.replace('\','\\'))`&quot;} WHERE AssocClass = Win32_DiskDriveToDiskPartition&quot;

foreach($part in $partitions)

{

Out-Host -InputObject &quot;`tPartition: $($part.name)&quot;

$vols = gwmi -Query &quot;ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`&quot;$($part.DeviceID)`&quot;} WHERE AssocClass = Win32_LogicalDiskToPartition&quot;

foreach($vol in $vols)

{

out-host -InputObject &quot;`t`t$($vol.name)&quot;

}

}

}

</pre></p>
<p>Not too bad, but could be better. There is a GetRelated method that PowerShell tack on to WMI objects which should allow you to do the Associate stuff with PowerShell rather than writing WMI queries but I havent figured that out.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/185/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/185/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/185/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=185&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2011/12/12/using-wmi-to-link-a-disk-volume-to-a-physical-disk-with-powershell/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>The Trouble with Format-* Commands in PowerShell</title>
		<link>http://jrich523.wordpress.com/2011/11/25/the-trouble-with-format-commands-in-powershell/</link>
		<comments>http://jrich523.wordpress.com/2011/11/25/the-trouble-with-format-commands-in-powershell/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 16:51:47 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[format-list]]></category>
		<category><![CDATA[format-table]]></category>
		<category><![CDATA[format-wide]]></category>
		<category><![CDATA[select]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=170</guid>
		<description><![CDATA[There are a handful of Format commands that can really help make your data easier to look at. Format-List (FL) Format-Custom (FC) Format-Table (FT) Format-Wide (FW) I&#8217;ll commonly use either Format-List or Format-Table to display the data of an object in the console to see whats in there but I often times see people put this in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=170&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There are a handful of Format commands that can really help make your data easier to look at.</p>
<ul>
<li>Format-List (FL)</li>
<li>Format-Custom (FC)</li>
<li>Format-Table (FT)</li>
<li>Format-Wide (FW)</li>
</ul>
<p>I&#8217;ll commonly use either Format-List or Format-Table to display the data of an object in the console to see whats in there but I often times see people put this in their scripts or even worse, in the middle of a pipe.</p>
<p><strong>Side Note:</strong> Another common mistake is for people to use write-host in a script, see <a href="http://blog.usepowershell.com/2011/04/write-host-does-just-and-only-that/">this</a>.</p>
<p>The problem with using the Format commands is that it is for displaying info and when it does this it converts your object to a special internal type object. Lets play with an IPAddress and see what we have.</p>
<p><pre class="brush: powershell;">

$ip = [ipaddress] '192.168.1.1'

$ip

$ip | ft

$ip | gm

$ip | ft | gm

</pre></p>
<p>So if you take a look at the output you&#8217;ll see a couple of things,</p>
<ol>
<li>The default view of an IP object is a List view. Some objects have default definitions for views and are stored in format files here C:\Windows\System32\WindowsPowerShell\v1.0 (NEVER EDIT THIS FILE), if you want to know more about these format files comment on this post and I&#8217;ll do a write up. If a default view isnt defined (which most arent) the rule is, more than 4 properties make it a list, 4 or less make it a table.)</li>
<li>If we ask for it as a table it will squeeze it in, which in some cases that&#8217;s great. (Dont forget ft -auto)</li>
<li>Running Get-Member (GM) on this we see that as it goes down the pipe its left in tact (Shows us we have an IPAddress object)</li>
<li>The important part, if we pass an object down the pipe and then format it and then check the type, we see several items spit back, all of which are Internal.Format types.</li>
</ol>
<p>The problem here is that what we&#8217;ve started with in the pipe (an IPAddress) has been dropped and changed for Format objects, which dont have the properties of the original object.</p>
<p>Basically we&#8217;ve gone from an Object to formatted text which is no fun in PowerShell.</p>
<p>There are some cases where you want to slim down your result set or combine things in which case the cmdlet you are looking for is Select-Object (Select) which I&#8217;ve now started to use over the format cmdlets for displaying data in the console.</p>
<p><pre class="brush: powershell;">

$ip | select address
$ip | select address | gm

</pre></p>
<p>You&#8217;ll notice the object type is only slightly different. the type name has been prefixed with Selected. The thing to keep in mind is if we try to use this IPAddress in a method that expects this object in its full state, for example.</p>
<p><pre class="brush: powershell;">
$ip = [ipaddress] &quot;...&quot; #use a valid IP here
$limitedIP = $ip | select addressfamily
$ip | gm
$limitedIP | gm
[net.dns]::GetHostEntry
[net.dns]::GetHostEntry($limitedIP)
[net.dns]::GetHostEntry($ip)
</pre></p>
<p>You&#8217;ll notice the first call caused an error saying there is no overload that has a single argument which is rather misleading because both signatures require only one argument (IPAddress or String). It should probably say invalid type or something like that.</p>
<p>The second call works just fine.</p>
<p>Now, back to the format cmdlets. Normally I would have stopped right here but the PowerShell.com Tip of the Day had a pretty neat use of Format-Table in a function</p>
<p><pre class="brush: powershell;">

$Input | Format-Table -AutoSize | Out-File $Path -Width 10000

</pre></p>
<p>This is actually a pretty neat use since it can be used to generate a report. I havent played with this enough to see if there is a great advantage of this method over the Export-CSV cmdlet, but still, it&#8217;s a use of the format commands in the pipe (never say never).</p>
<p>I hope this has helped clear things up for you more than making it worse. I will say I think one of the primary take aways from this post is that with all power that PowerShell provides its VERY easy to get yourself in trouble.</p>
<p><strong>BONUS TIP:</strong> You can create custom objects quickly with Select like so.</p>
<p><pre class="brush: powershell;">

$customobj = &quot;&quot; | select fname,lname
$customobj.fname = 'Justin'
$customobj.lname = 'Rich'

</pre></p>
<p>Enjoy!</p>
<p>&nbsp;</p>
<p>P.S. Thanks to Thomas Lee for the corrections.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/170/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/170/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/170/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=170&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2011/11/25/the-trouble-with-format-commands-in-powershell/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
		<item>
		<title>Modify a SharePoint 2010 (probably 2007 as well) Wiki page with PowerShell</title>
		<link>http://jrich523.wordpress.com/2011/11/14/modify-a-sharepoint-2010-probably-2007-as-well-wiki-page-with-powershell/</link>
		<comments>http://jrich523.wordpress.com/2011/11/14/modify-a-sharepoint-2010-probably-2007-as-well-wiki-page-with-powershell/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 20:53:18 +0000</pubDate>
		<dc:creator>jrich</dc:creator>
				<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[WMF (Powershell/WinRM)]]></category>
		<category><![CDATA[modify]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[sharepoint]]></category>
		<category><![CDATA[wiki]]></category>

		<guid isPermaLink="false">http://jrich523.wordpress.com/?p=160</guid>
		<description><![CDATA[This turned out to be much harder than I expected, so I thought it would be worth sharing. First, you ask, why Web Services? Simple, I wanted this script to work from anywhere. with any other methods of accessing SharePoint you need to be on the server for it to work, so Web Services it is. First [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=160&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This turned out to be much harder than I expected, so I thought it would be worth sharing.</p>
<p>First, you ask, why Web Services? Simple, I wanted this script to work from anywhere. with any other methods of accessing SharePoint you need to be on the server for it to work, so Web Services it is.</p>
<p>First step, getting a handle on your SharePoint server. PowerShell has a cmdlet for that!</p>
<p><a href="http://technet.microsoft.com/en-us/library/dd315258.aspx">New-WebServiceProxy</a></p>
<p>

$proxy = New-WebServiceProxy 'http://localhost/_vti_bin/lists.asmx' -UseDefaultCredential

</p>
<p>I just used local host for testing, but it works with any server and you have to specify the site, which in this case I used the default root site. I also passed my logged in creds but you can specify creds if need be.</p>
<p><strong>NOTE:</strong> I found that the URL didnt always stay as it was suppose to so verify that and update it if need be.</p>
<p>If you want to modify/add/delete data you&#8217;ll likely want to use the List Web Service, but remember there are others (<a href="http://msdn.microsoft.com/en-us/library/ms479390(office.12).aspx">http://msdn.microsoft.com/en-us/library/ms479390(office.12).aspx</a> )</p>
<p>Now that we have this List Web Service, how do we work with it? You can poke around a bit with PowerShell</p>
<p><pre class="brush: plain;">

$proxy | get-member

</pre></p>
<p>Whole lot of things there, but since its a Web Service, we want to look at methods (<a href="http://msdn.microsoft.com/en-us/library/lists.lists_members(office.12).aspx">list of members here</a>)</p>
<p>There are a handful of Get methods, but the <a href="http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems(office.12).aspx">GetListItems</a> seems to be what we are looking for. If we check the signature we see that a few things are required.</p>
<ul>
<li>ListName</li>
<li>ViewName</li>
<li>Query</li>
<li>ViewFields</li>
<li>RowLimit</li>
<li>QueryOptions</li>
</ul>
<p>Lot of info just to get a list item so lets start to tackle this.</p>
<p>ListName &#8211; Simple one, a string of the list we want to work with, in my case its &#8220;myWiki&#8221; but, as per the docs, its better to use the GUID (get in to that later).</p>
<p>ViewName &#8211; This is a string/GUID of the view we want to use, but its optional, so I found it was easy enough to leave blank for my needs.</p>
<p>Query &#8211; An XML node of CAML that defines what to return.</p>
<p>ViewFields &#8211; An XML node of more CAML to define what views we want to see (this one is important).</p>
<p>RowLimit &#8211; Pretty obvious, the default (all) is what we want.</p>
<p>QueryOptions &#8211; An XML node of CAML for the query options</p>
<p>Not too bad once we start to look at it, but whats this CAML?</p>
<p>CAML &#8211; Collaborative Application Markup Language, its just XML with named tags (same idea as HTML)</p>
<p>I dont know much about CAML, and I spent a good deal of time digging, but what I found is that there is a tool for it!</p>
<p><a href="http://www.u2u.be/Tools/wincamlquerybuilder/CamlQueryBuilder.aspx">http://www.u2u.be/Tools/wincamlquerybuilder/CamlQueryBuilder.aspx</a></p>
<p>This tool was a HUGE help. I&#8217;m not going to go in to details because it was fairly easy to use, and when you see the CAML I provide it will make more sense.</p>
<p>Now that we have a method and a way to build the queries, lets get off and running.</p>
<p>Using the U2U Caml builder (tweaking it a bit) I came up with this to get back the one record I&#8217;d like to modify.</p>
<p><pre class="brush: xml;">

&lt;mylistitemrequest&gt;
&lt;Query&gt;
&lt;Where&gt;
&lt;Eq&gt;
&lt;FieldRef ID=&quot;ID&quot; /&gt;
&lt;Value Type=&quot;Counter&quot;&gt;5&lt;/Value&gt;
&lt;/Eq&gt;
&lt;/Where&gt;
&lt;/Query&gt;
&lt;ViewFields&gt;
&lt;FieldRef Name='WikiField'/&gt;
&lt;/ViewFields&gt;
&lt;QueryOptions&gt;
&lt;IncludeMandatoryColumns&gt;FALSE&lt;/IncludeMandatoryColumns&gt;
&lt;/QueryOptions&gt;
&lt;/mylistitemrequest&gt;

</pre></p>
<p>You&#8217;ll notice there are a few key words there that stick out, Query, ViewFields and QueryOptions which nicely match up with our method arguments!</p>
<p><pre class="brush: plain;">

$str = @'
&lt;mylistitemrequest&gt;&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef ID=&quot;ID&quot; /&gt;
&lt;Value Type=&quot;Counter&quot;&gt;5&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;
&lt;/Query&gt;&lt;ViewFields&gt;&lt;FieldRef Name='WikiField'/&gt;&lt;/ViewFields&gt;&lt;QueryOptions&gt;
&lt;IncludeMandatoryColumns&gt;FALSE&lt;/IncludeMandatoryColumns&gt;&lt;/QueryOptions&gt;&lt;/mylistitemrequest&gt;
'@
($xml = [xml]&quot;&quot;).LoadXml($str)

$query = $xml.SelectSingleNode('//Query')
$view = $xml.SelectSingleNode('//ViewFields')
$options = $xml.SelectSingleNode('//QueryOptions')

$wiki = $proxy.GetListItems(&quot;myWiki&quot;,&quot;&quot;,$query,$view,&quot;&quot;,$options,&quot;&quot;)

</pre></p>
<p>So we took that XML document object and ripped out the nodes and feed the nodes in to the method and stored its results in to $wiki.</p>
<p>Running Get-Member against our $wiki will show us that we have an XML document that we can dig in to.</p>
<p>$wiki.data will show us that there is one item in there, just what we were looking for.</p>
<p>$wiki.data.row will show us the fields of a wiki, the one we really care about is the content of that wiki which is ows_wikifield</p>
<p>$wiki.data.row.ows_wikifield</p>
<p>Some pretty basic HTML in there, in my case I get back this</p>
<p><pre class="brush: xml;">

&lt;div&gt;&lt;table id=&quot;layoutsTable&quot; style=&quot;width:100%&quot;&gt;&lt;tbody&gt;&lt;tr style=&quot;vertical-align:top&quot;&gt;&lt;t
d style=&quot;width:100%&quot;&gt;&lt;div style=&quot;width:100%&quot;&gt;&lt;div&gt;&lt;p&gt;here&lt;/p&gt;
&lt;p&gt;is some&lt;/p&gt;
&lt;p&gt;sample data&lt;/p&gt;
&lt;p&gt;i want to add&lt;/p&gt;
&lt;p&gt;after this&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
&lt;span id=&quot;layoutsData&quot; style=&quot;display:none&quot;&gt;false,false,1&lt;/span&gt;&lt;/div&gt;

</pre></p>
<p>Now lets tack on some text to the end of our wiki</p>
<p><pre class="brush: plain;">

$content = $wiki.data.row.ows_WikiField
$content = $content -replace &quot;&lt;p&gt;after this&lt;/p&gt;&quot;, &quot;&lt;p&gt;after this&lt;/p&gt;&lt;p&gt;yay more data&lt;/p&gt;&quot;

</pre></p>
<p>We&#8217;ve updated the text, but now we have to inject that back in to our Wiki, which involves a new method and more CAML. I&#8217;m not going to bother explaining it because if you&#8217;ve followed whats above, the update will make sense.</p>
<p><pre class="brush: plain;">

$updatestr = @&quot;
&lt;Batch OnError=&quot;Continue&quot;&gt;
&lt;Method ID='1' Cmd='Update'&gt;
&lt;Field Name='ID'&gt;3&lt;/Field&gt;
&lt;Field Name='WikiField'&gt;
test
&lt;/Field&gt;&lt;/Method&gt;&lt;/Batch&gt;
&quot;@

($xml= [xml]&quot;&quot;).loadXml($updatestr)
$xml.batch.Method.Field[1].&quot;#text&quot; = $content

$proxy.UpdateListItems(&quot;myWiki&quot;,$xml)

</pre></p>
<p>There is one part that should be making you scratch your head, and let me tell you, it took a while for me to figure out.</p>
<p>Why did i put &#8220;test&#8221; in the XML wikifield?</p>
<p>well, come to find out, if you dump HTML in there, it looks an aweful lot like XML. If you dont put anything then the #text field isnt generated, so i put &#8220;test&#8221; in there and then used the XML members to inject the actual content I wanted updated.</p>
<p>Was a bit of a trick figuring this out, so I hope it helps!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/jrich523.wordpress.com/160/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/jrich523.wordpress.com/160/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/jrich523.wordpress.com/160/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/jrich523.wordpress.com/160/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/jrich523.wordpress.com/160/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/jrich523.wordpress.com/160/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/jrich523.wordpress.com/160/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/jrich523.wordpress.com/160/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=jrich523.wordpress.com&amp;blog=12000032&amp;post=160&amp;subd=jrich523&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://jrich523.wordpress.com/2011/11/14/modify-a-sharepoint-2010-probably-2007-as-well-wiki-page-with-powershell/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<georss:point>42.358800 -71.124700</georss:point>
		<geo:lat>42.358800</geo:lat>
		<geo:long>-71.124700</geo:long>
		<media:content url="http://0.gravatar.com/avatar/68df007616edc4ed449c82a356178a4f?s=96&#38;d=&#38;r=G" medium="image">
			<media:title type="html">jrich</media:title>
		</media:content>
	</item>
	</channel>
</rss>
