<?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/"
	>

<channel>
	<title>Windows Server HQ by Train Signal.com &#187; PowerShell Scripting</title>
	<atom:link href="http://windowsserver.trainsignal.com/tag/powershell-scripting/feed" rel="self" type="application/rss+xml" />
	<link>http://windowsserver.trainsignal.com</link>
	<description>We are here to help you learn Windows Server!</description>
	<lastBuildDate>Wed, 21 Jul 2010 16:34:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PowerShell 2.0: Server 2008 R2 Top New Management Feature</title>
		<link>http://windowsserver.trainsignal.com/powershell-2-0-server-2008-r2</link>
		<comments>http://windowsserver.trainsignal.com/powershell-2-0-server-2008-r2#comments</comments>
		<pubDate>Wed, 12 May 2010 14:00:10 +0000</pubDate>
		<dc:creator>Brian Nelson</dc:creator>
				<category><![CDATA[Server 2008 R2]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[PowerShell 2.0]]></category>
		<category><![CDATA[PowerShell Scripting]]></category>
		<category><![CDATA[Server 2008]]></category>
		<category><![CDATA[Windows 7]]></category>

		<guid isPermaLink="false">http://windowsserver.trainsignal.com/?p=7496</guid>
		<description><![CDATA[PowerShell Scripting on Windows Server 2008 R2
 PowerShell 1.0 gave systems administrators around the world a new administration tool when it was introduced with Windows Server 2003. 
For years, Microsoft has worked to develop a graphical user interface, or GUI, that would make system administration and user administration easier and more user friendly. 
In many [...]

<h3>Related posts:<ul><li><a href='http://windowsserver.trainsignal.com/ad-powershell-scripts-management-tool' rel='bookmark' title='Permanent Link: Active Directory PowerShell Scripts Management Tool For Admins'>Active Directory PowerShell Scripts Management Tool For Admins</a></li>
<li><a href='http://windowsserver.trainsignal.com/dont-be-afraid-of-windowspowershell' rel='bookmark' title='Permanent Link: Don’t be Afraid of PowerShell'>Don’t be Afraid of PowerShell</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 1'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 1</a></li>
</ul></h3>]]></description>
			<content:encoded><![CDATA[<h2>PowerShell Scripting on Windows Server 2008 R2</h2>
<p><img src="http://windowsserver.trainsignal.com/wp-content/uploads/2010/05/powershell1.jpg" alt="" title="PowerShell 2.0" width="200" height="155" class="float" class="alignleft size-full wp-image-7521" /> <a href="http://windowsserver.trainsignal.com/windows-server-2008-powershell">PowerShell 1.0</a> gave systems administrators around the world a new administration tool when it was introduced with Windows Server 2003. </p>
<p>For years, Microsoft has worked to develop a graphical user interface, or GUI, that would make system administration and user administration easier and more user friendly. </p>
<p>In many ways, the company succeeded admirably. </p>
<p>Most admins know at least one or two people who have managed to create a user in a very small Windows Server environment through User Manager and think that they should become a Windows Administrator because they already understand &#8220;how to do it.&#8221;</p>
<p>However, for administrators in environments where users exceed the number of people it takes to field a couple softball teams, things  are more complicated. In fact, one of the difficulties of properly administering a networked operating system and its servers is keeping all the &#8220;little things&#8221; consistent across the enterprise. Forgetting a check-box here, and a radio button there, can add up to a security nightmare waiting to happen, or perhaps, a very angry Vice President unable to remotely connect at a critical time.</p>
<p>The solution to some of these problems has been scripting. By writing scripts, Windows system engineers could ensure that repetitive tasks happened correctly and with far less effort than doing them manually. Everything from creating new user accounts, to installing software and upgrades, to basic login scripts has been coded somewhere along the way by a savvy systems admin looking to avoid headaches and spend a little less time on repetitive tasks.</p>
<p><span id="more-7496"></span><br />
Eventually, new Windows Server features and enhancements began to outstrip the capabilities of the DOS-based scripting that server administrators had been cobbling together. Fortunately, new tools and utilities were also developed that helped reduce some of the reliance on login scripts. For example, User and Group profiles have long since made mapping drive letters via login script obsolete. However, administrators still needed a more powerful scripting environment.</p>
<h2>PowerShell 2.0 Upgrades Features and Capabilities</h2>
<p>PowerShell has been slightly underrated within the administrator community. One reason is that in order for PowerShell to really perform throughout the enterprise, it needs to be usable on the servers and all the desktops. </p>
<p>Fortunately, Windows 7 comes ready to execute PowerShell scripts. Windows 7 SP1 is set to ship in the near future, which sounds the bell for many long-time IT professionals who live by the rule to always wait for SP1 before upgrading, and Server 2008 R2 comes with PowerShell 2.0 installed by default. As <a href="http://www.trainsignaltraining.com/deploy-windows-7-enterprise/2009-08-19/">Windows 7 is installed in the enterprise</a>, PowerShell 2.0 will grow even more useful.</p>
<p>Another reason PowerShell has not gotten its fair share of affection from systems administrators is that there were a few nagging things about how PowerShell worked conspiring to make it seem less powerful than it actually was. However, Microsoft has addressed many of these issues and thrown in a few new features as well.</p>
<p>Let&#8217;s take a look at some of these new features now.</p>
<h3>Remoting</h3>
<p>Nothing has been a bigger thorn in the side of PowerShell than Remoting. Remoting is the ability to run commands via PowerShell on remote computers. Technically, some remoting was possible in PowerShell one, but it was limited to the Get-WMIObject cmdlet within Windows Management Instrumentation (WMI). Even worse, WMI required RPC connections which meant having to go to the networking guys to get ports opened and firewall exceptions allowed. Not fun.</p>
<p>PowerShell 2.0 allows administrators to run commands on remote computers using the WS-Man (WS-Management) protocols which establish secure connections to remote computers using ports 80 and 443 by default. In many environments these ports will already be open, and in those that they are not, they’ll be a much easier sell to the networking team.</p>
<p>There is one little catch to remoting in PowerShell 2.0. In order to use remoting, it must be enabled on both machines. However, this only needs to be done once. Once enabled, remoting can be used on multiple machines at the same time allowing the administrator to execute the same commands on several computers at once. The applications for this ability are limited only by the admin’s ability (and the availability of the right cmdlet).</p>
<h3>New cmdlets</h3>
<p>Speaking of cmdlets, PowerShell 2.0 comes with over 100 built-in cmdlets. While this covers a lot of ground, there is no doubt that Microsoft Server administrators will quickly find functions and tasks that require other commands. Fortunately, Microsoft has implemented a way to handle this eventuality as well. </p>
<p>Modules are also new to PowerShell 2.0 and allow script developers to organize code into self-contained reusable units. This functionality has already been used to create a PowerShell 2.0 Active Directory Module which brings more possibilities to managing Active Directory via PowerShell.</p>
<h3>Run Background Jobs in PowerShell</h3>
<p>Another big addition to the PowerShell feature set is the ability to run background jobs. This means that those PowerShell scripts that take a long time to run can continue to perform in the background while the command prompt returns control immediately to the console. </p>
<p>An admin performing numerous tasks late at night can get them all running right away instead of having to wait until 2:00 AM to run that last command. This is especially useful while remoting multiple machines, especially when those machines are separated by various network connection speeds.</p>
<p><img src="http://windowsserver.trainsignal.com/wp-content/uploads/2010/05/powershell2.jpg" alt="" title="PowerShell 2.0" width="520" height="478" class="alignleft size-full wp-image-7522" /></p>
<h3>System Events Integration</h3>
<p>PowerShell 2.0 now offers the ability to monitor and act on system events which can allow for more proactive scripting.</p>
<h3> PowerShell ISE GUI</h3>
<p>The most curious edition to PowerShell 2.0 is the PowerShell GUI, which, on the surface, appears to defeat the whole point of PowerShell. However, the GUI is really more of a basic script editor complete with color coded syntax, partial execution, stepping, and graphic debugging. The GUI also includes context sensitive help which can save admins from scanning through the verbose output of some help commands.</p>
<p>With Windows 7 coming to many businesses in the near future and the upcoming release of Windows Server 2008 R2 SP1, PowerShell 2.0 will be already waiting to go for enterprise-wide control and administration. The time is now for Microsoft systems engineers and administrators to learn how to take advantage of PowerShell 2.0.</p>
<p>&nbsp;</p>
<h2>PowerShell 2.0 Demonstration</h2>
<p>Take a look at the video below to see a short demo of PowerShell 2.0.</p>
<p>&nbsp;<br />
<script src="http://technet.microsoft.com/objectforward/default.aspx?type=VideoPlayer&#038;video=http%3A%2F%2Fdownload.microsoft.com%2Fdownload%2FC%2FB%2F7%2FCB7BD324-E9B6-4D3F-854D-8AD4FDBE5CA4%2Fpowershell.wmv&#038;thumb=http%3A%2F%2Fi.technet.microsoft.com%2Fdd320288.WindowsPowerShell2L(en-us%252cMSDN.10).jpg&#038;title=&#038;width=400&#038;height=400" type="text/javascript"></script></p>


<h3>Related posts:<ul><li><a href='http://windowsserver.trainsignal.com/ad-powershell-scripts-management-tool' rel='bookmark' title='Permanent Link: Active Directory PowerShell Scripts Management Tool For Admins'>Active Directory PowerShell Scripts Management Tool For Admins</a></li>
<li><a href='http://windowsserver.trainsignal.com/dont-be-afraid-of-windowspowershell' rel='bookmark' title='Permanent Link: Don’t be Afraid of PowerShell'>Don’t be Afraid of PowerShell</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 1'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 1</a></li>
</ul></h3>]]></content:encoded>
			<wfw:commentRss>http://windowsserver.trainsignal.com/powershell-2-0-server-2008-r2/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Don’t be Afraid of PowerShell</title>
		<link>http://windowsserver.trainsignal.com/dont-be-afraid-of-windowspowershell</link>
		<comments>http://windowsserver.trainsignal.com/dont-be-afraid-of-windowspowershell#comments</comments>
		<pubDate>Sat, 01 Aug 2009 00:00:54 +0000</pubDate>
		<dc:creator>Lisa Szpunar</dc:creator>
				<category><![CDATA[Windows Server]]></category>
		<category><![CDATA[Command Shell]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[PowerShell Scripting]]></category>
		<category><![CDATA[Server Admin]]></category>

		<guid isPermaLink="false">http://windowsserver.trainsignal.com/?p=6626</guid>
		<description><![CDATA[What is PowerShell?
PowerShell is Microsoft’s newish extensible scripting language and corresponding command line shell. PowerShell was specifically made for IT professionals to achieve greater productivity and control system administration more easily. 
What PowerShell Can Help You Do
The thing is, PowerShell can do pretty much anything except walk your dog for you. You can even check the [...]

<h3>Related posts:<ul><li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 1'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 1</a></li>
<li><a href='http://windowsserver.trainsignal.com/ad-powershell-scripts-management-tool' rel='bookmark' title='Permanent Link: Active Directory PowerShell Scripts Management Tool For Admins'>Active Directory PowerShell Scripts Management Tool For Admins</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell-2' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 2'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 2</a></li>
</ul></h3>]]></description>
			<content:encoded><![CDATA[<h2>What is PowerShell?</h2>
<p>PowerShell is Microsoft’s newish extensible scripting language and corresponding command line shell. PowerShell was specifically made for IT professionals to achieve greater productivity and control system administration more easily. </p>
<h2>What PowerShell Can Help You Do</h2>
<p>The thing is, PowerShell can do pretty much anything except walk your dog for you. You can even check the date and time if you really wanted to. I guess you could stop using the command line all together and do all your cmd tasks from within the PowerShell shell. </p>
<p>However, the real fun comes in when you can use PowerShell to make your sysadmin life easier. Here are a few random examples:</p>
<ul>
<li>Inventory your servers like what each has, the free memory, what service pack it is running, and so on.</li>
<p></p>
<li>Add multiple users at once to your AD and then give them all a mailbox in Exchange.</li>
<p></p>
<li>Back up and sync certain files then email yourself a corresponding log file&#8230;every night.</li>
<p></p>
<li>Test out those scary commands before committing to them using the <em>Whatif</em> feature.</li>
<p></p>
<li>And maybe the most compelling thing: You know how in Server 2008 R2 you can recover an AD object from the recycle bin after you have – oops – deleted it? Well you won’t find that option anywhere in the GUI. You need PowerShell to do it. If that isn’t a reason to give PowerShell a try then I don’t know what is!</li>
</ul>
<p><span id="more-6626"></span></p>
<h2>For the Newbies</h2>
<p>Good News! You don’t need any prior programming experience to use PowerShell &#8212; it is that intuitive. But, just so we are on the same page here is a short vocab lesson:</p>
<ul>
<li><strong>Shell</strong> – What you the user actually interacts with. Either a command line or a GUI (graphical user interface).</li>
<p></p>
<li><strong>Extensible</strong> – The ability of a system to grow and change as needed.</li>
<p></p>
<li><strong>Scripting Language</strong> – Well, there are numerous debates going on all over creation about the difference between a programming language and a scripting language. You don’t really need to understand the specifics to understand that PowerShell is a language that you use to do administrative tasks. Who cares whether it is interpreted or compiled?</li>
<p></p>
<li><strong>cmdlets</strong> – Pronounced <em>command-lets</em>. Cmdlets are simple tools that can be used separately, but their power is realized when you combine these simple tools to perform complex tasks. Microsoft provides buckets of built-in cmdlets  but you can write you own if you see fit.</li>
</ul>
<h2>For the People with Programming or Unix Experience</h2>
<p>Not surprisingly PowerShell has all the comforts of home: man pages, aliases, wildcards, and pipelines; if statements, recursion, and loops.</p>
<p>If you have worked with VB or WHS then you should be able to make the translation pretty easily. There is even <a title="The VBScript-to-Windows PowerShell Conversion Guide" href="http://www.microsoft.com/technet/scriptcenter/topics/winpsh/convert/default.mspx" target="_blank">help for translating your existing VB scripts to PowerShell</a>.</p>
<h2>Resources to Get You Started</h2>
<ul>
<li><a title="Take Command of Server 2008 with Windows PowerShell" href="http://windowsserver.trainsignal.com/windows-server-2008-powershell">Jason Ensinger’s articles on PowerShell right here at Windows Server HQ</a></li>
<li><a title="PowerShell FAQ" href="http://www.microsoft.com/windowsserver2008/en/us/powershell-faq.aspx" target="_blank">PowerShell FAQ</a></li>
<li><a title="Windows PowerShell Owners Manual" href="http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/default.mspx" target="_blank">Windows PowerShell Owners Manual</a></li>
<li><a title="Scripting with Windows PowerShell" href="http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx" target="_blank">Scripting with Windows PowerShell</a></li>
<li><a title="Windows PowerShell Blog" href="http://blogs.msdn.com/powershell/default.aspx" target="_blank">Windows PowerShell Blog</a></li>
<li><a title="Windows PowerShell Cookbook" href="http://oreilly.com/catalog/9780596528492/index.html" target="_blank">Windows PowerShell Cookbook</a> &#8211; The term cookbook describes how the book provides recipes to do specific tasks  with PowerShell. A super cute concept if you ask me.</li>
</ul>
<h2> Good luck!</h2>


<h3>Related posts:<ul><li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 1'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 1</a></li>
<li><a href='http://windowsserver.trainsignal.com/ad-powershell-scripts-management-tool' rel='bookmark' title='Permanent Link: Active Directory PowerShell Scripts Management Tool For Admins'>Active Directory PowerShell Scripts Management Tool For Admins</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell-2' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 2'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 2</a></li>
</ul></h3>]]></content:encoded>
			<wfw:commentRss>http://windowsserver.trainsignal.com/dont-be-afraid-of-windowspowershell/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Take Command of Server 2008 with Windows PowerShell &#8211; Part 4</title>
		<link>http://windowsserver.trainsignal.com/windows-server-2008-powershell-4</link>
		<comments>http://windowsserver.trainsignal.com/windows-server-2008-powershell-4#comments</comments>
		<pubDate>Thu, 21 Feb 2008 16:30:48 +0000</pubDate>
		<dc:creator>Jason Ensinger</dc:creator>
				<category><![CDATA[Server 2008]]></category>
		<category><![CDATA[cmdlets]]></category>
		<category><![CDATA[Command Prompt]]></category>
		<category><![CDATA[Command Shell]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[PowerShell Scripting]]></category>

		<guid isPermaLink="false">http://www.trainsignaltraining.com/windows-server-2008-powershell-4/2008-02-21/</guid>
		<description><![CDATA[In the last couple of weeks you were introduced to the basics of Windows PowerShell, Microsoft&#8217;s new command shell environment.
In Part 1 I talked about what PowerShell is and showed you how to install and access it on Windows Server 2008.
In Part 2 we went over PowerShell cmdlets and PowerShell providers. I showed you how [...]

<h3>Related posts:<ul><li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell-2' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 2'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 2</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell-3' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 3'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 3</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 1'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 1</a></li>
</ul></h3>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.trainsignaltraining.com/wpnew/wp-content/uploads/2008/01/PowerShell2.jpg" alt="Windows PowerShell" title="Windows PowerShell" align="right" width="251" height="200" border="0" />In the last couple of weeks you were introduced to the basics of <strong>Windows PowerShell</strong>, Microsoft&#8217;s new command shell environment.</p>
<p>In <a href="http://windowsserver.trainsignal.com/windows-server-2008-powershell"><strong>Part 1</strong></a> I talked about what PowerShell is and showed you how to install and access it on Windows Server 2008.</p>
<p>In <a href="http://windowsserver.trainsignal.com/windows-server-2008-powershell-2"><strong>Part 2</strong></a> we went over PowerShell cmdlets and PowerShell providers. I showed you how to execute cmdlets and work with the objects returned and also how to use the different PowerShell providers to work with server resources inaccessible from the FileSystem provider.</p>
<p>In <a href="http://windowsserver.trainsignal.com/windows-server-2008-powershell-3/"><strong>Part 3</strong></a> we learned how to customize the user interface with the PowerShell profile.</p>
<p>And now that you are familiar with the capabilities of PowerShell, it is time to learn how to really unleash the power of PowerShell with PowerShell scripting.</p>
<p>Today I&#8217;ll show you how to take advantage of the script engine to automate the performance of Administrative tasks on the Server.</p>
<p><span id="more-423"></span></p>
<h3>Understanding PowerShell Scripting</h3>
<p>If you followed along with the PowerShell customization exercise that I showed you in <a href="http://windowsserver.trainsignal.com/windows-server-2008-powershell-3">the last article</a>, you already know how to create PowerShell scripts. The profile file created in that exercise is actually a PowerShell Script.</p>
<p>In essence, a PowerShell script is simply a text file containing a list of PowerShell commands saved with the file extension .ps1.</p>
<p>For security purposes, script execution is disabled by default. You can set the script execution policy with the <code>Set-ExecutionPolicy</code> cmdlet.</p>
<p>The parameters available for the <code>Set-ExecutionPolicy</code> cmdlet are: <code>-restricted</code>, <code>-unrestricted</code>, <code>-remotesigned</code> and <code>–allsigned</code>. Enter the command: <code>Get-Help Set-ExecutionPolicy –detailed</code> for details on the <code>Set-ExecutionPolicy</code> cmdlet parameters.</p>
<p>In order to exhibit the capabilities of the PowerShell script engine we will go over a sample PowerShell script. The example script was created to display the potential of PowerShell scripting for performing administrative tasks in a server environment.</p>
<p>When the example script is ran, it behaves like a program. It first lists all the printers installed on the server and then prompts you to select one or all of the printers.</p>
<p>Once a printer is selected an additional menu is displayed for operations that can be performed with the printer or printers. When an action is selected, it is performed, then the program begins again at the beginning until you enter ‘exit’ at one of the prompts.</p>
<p>If we examine the script, we can see that it is broken up into three sections. The first section is dedicated to the function definition portion of the script. The second section covers the process of prompting the user. The third section is where the operation chosen is performed on the selected printer.</p>
<pre>
function cancelPrinterJobs {
	$objPrinter = $args[0]
	$objCancel = $objPrinter.CancelAllJobs()
	if ($objCancel.ReturnValue -eq 0) {
		write-host "Cancelled all jobs on"$objPrinter.Name
	}
	else {
		write-host "Cancel of all jobs on"$objPrinter.Name"failed"
	}
}

function pausePrinter {
	$objPrinter = $args[0]
	$objPause = $objPrinter.Pause()
	if ($objPause.ReturnValue -eq 0) {
		write-host $objPrinter.Name"pause"
	}
	else {
		write-host "Pause of"$objPrinter.Name"failed"
	}
}

function resumePrinter {
	$objPrinter = $args[0]
	$objResume = $objPrinter.Resume()
	if ($objResume.ReturnValue -eq 0) {
		write-host $objPrinter.Name" resumed"
	}
	else {
		write-host "Resume of"$objPrinter.Name"failed"
	}
}

function testPrinter {
	$objPrinter = $args[0]
	$objTest = $objPrinter.PrintTestPage()
	if ($objTest.ReturnValue -eq 0) {
		write-host $objPrinter.Name" printed a test page"
	}
	else {
		write-host $objPrinter.Name" test page failed"
	}
}

function setDefaultPrinter {
	$objPrinter = $args[0]
	$objDefault = $objPrinter.SetDefaultPrinter()
	if ($objDefault.ReturnValue -eq 0) {
		write-host $objPrinter.Name" Set as default."
	}
	else {
		write-host "Failed to set"$objPrinter.Name"as default"
	}
}

function writePrinterInfo {
	$objPrinter = $args[0]
	$strComputerName = $args[1]
	$colPrinters = get-wmiobject -class "Win32_PrinterConfiguration" -namespace "root\CIMV2" -computername $strComputerName

	write-host $objPrinter.Name "Printer Information"
	write-host
	write-host "Name: " $objPrinter.Name
	write-host "Driver Name: " $objPrinter.DriverName
	write-host "Port Name: " $objPrinter.PortName
	write-host "Shared: " $objPrinter.Shared
	write-host "Share Name: " $objPrinter.ShareName
	write-host "Queued: " $objPrinter.Queued
	write-host "Status: " $objPrinter.Status

	foreach ($objPrinter in $colPrinters) {
		if ($objPrinter.Name -eq $strPrinterName) {
			write-host "Driver Version: " $objPrinter.DriverVersion
			write-host "Paper Size: " $objPrinter.PaperSize
			write-host "X Resolution: " $objPrinter.XResolution
			write-host "Y Resolution: " $objPrinter.YResolution
			write-host
			break
		}
	}
}
</pre>
<p>In the first section, six functions are defined. Each function performs an action with a printer. The function cmdlet is used to define each function. Immediately after the <code>function</code> cmdlet the function name is supplied, followed by the commands of the function enclosed in curly brackets.</p>
<p>Functions in PowerShell do not support defining the arguments. Instead, functions accept a virtually unlimited number of space-separated objects as arguments. The arguments can be accessed within the function with the $args variable.</p>
<p>When PowerShell executes a script, commands are executed as the script is read rather than loaded to memory and then executed. Therefore, a function must be defined in the script before it is ever called.</p>
<p>It is a good idea to always define all your functions first in a PowerShell script. If a function is called within another function the called function must be defined first.</p>
<p>The first commands of every function are to assign the expected argument to a variable for script readability. All the functions expect a WMI Printer object as the first argument. Only the last function expects a second argument, the computer name.</p>
<p>The first five functions each execute a method of the printer object and assign it to a variable. The return value is checked for successful execution with an &#8220;if&#8221; statement and if the conditions in the parentheses are met the <code>Write-Host</code> cmdlet in the curly brackets is executed to display a success message.</p>
<p>If the successful condition is not met a failure message is displayed from the command in the curly brackets of the else statement.</p>
<p>After the argument variables are assigned in the final function the <code>Get-WMIObject</code> cmdlet is used to assign the Win32_PrinterConfiguration object to a variable. Then select properties from the supplied Printer object are displayed.</p>
<p>After that the <code>Foreach-Object</code> cmdlet is used to loop through the items of the PrinterConfiguration object then checks if its name matches that of the Printer object supplied to the function. When a match is found select properties from the PrinterConfiguration object are displayed and the loop is exited with the <code>break</code> cmdlet.</p>
<pre>
cls

$strComputerName = "."
$colPrinters = get-wmiobject -class "Win32_Printer" -namespace "root\CIMV2" -computername $strComputerName | sort-object "Name"

do {
	$printerIndex = 0
	write-host
	write-host "Installed Printers"
	write-host
	write-host "0) All Printers"

	foreach ($objPrinter in $colPrinters) {
		$printerIndex = $printerIndex + 1
		write-host $printerIndex") "$objPrinter.Name
	}

	write-host

	$selectedPrinterIndex = read-host "Select the printer(s) you wish to work with or type 'exit' to exit"
	if ($selectedPrinterIndex -eq "exit") {
		break
	}
	$validated = 0
	do {
		if ($selectedPrinterIndex -gt $printerIndex) {
			$selectedPrinterIndex = read-host "Please enter a valid printer number"
		}
		else {	$validated = 1 }
	}
	while ($validated -lt 1)

	write-host
	write-host "Printer Operations"
	write-host
	write-host "0) Display Printer(s) Information"
	write-host "1) Cancel Printer(s) Jobs"
	write-host "2) Pause Printer(s)"
	write-host "3) Resume Printer(s)"
	write-host "4) Test Printer(s)"
	if ($selectedPrinterIndex -gt 0) {
		write-host "5) Set Printer As Default"
	}
	write-host

	$selectedOperationIndex = read-host "Select an action to perform on the printer or type 'exit' to exit"
	if ($selectedOperationIndex -eq "exit") {
		break
	}
	$validated = 0
	do {
		if ($selectedOperationIndex -gt 5) {
			$selectedOperationIndex = read-host "Please enter a valid operation number"
		}
		else {
			if ($selectedPrinterIndex -eq 0) {
				if ($selectedOperationIndex -eq 5) {
					$selectedOperationIndex = read-host "Please enter a valid operation number"
				}
				else {	$validated = 1 }
			}
			else {	$validated = 1 }
		}
	}
	while ($validated -lt 1)
</pre>
<p>The second section of the script is where execution begins. The program begins by clearing the console with the <code>cls</code> cmdlet. Next a variable is assigned with the computer name.</p>
<p>When a computer name is expected as a cmdlet parameter the dot used will be interpreted as the local machine. The computer name variable is then used when assigning the WMI Win32_Printer object to a variable.</p>
<p>The <code>DoWhile-Object</code> is executed next and is closed at the end of the script with <code>while (1)</code>. This tells the program to loop execution until the loop is exited with the <code>break</code> cmdlet.</p>
<p>The next four commands display the printer menu title and first option as 0 for selecting all printers. A variable is then created to keep track of the printer index before the <code>foreach-object</code> cmdlet is used to loop through the Printer objects of the Win32_Printer object. Each time through the loop one is added to the printer index then it is displayed with the name of the current Printer object.</p>
<p>After the loop a blank line is displayed to separate the menu items from the prompt. The prompt is displayed with the <code>Read-Host</code> cmdlet and the input is assigned to a variable to represent the index of the selected printer. The printer index variable is then checked if the value is exit and exits the main program loop if so.</p>
<p>A variable is then assigned the value of 0 to represent the input has not been validated. A Do While loop is set to loop until the validation variable equals 1. Enclosed in the loop is an if object that is used to check if the printer index exceeds the number of printers, if so, If the input is invalid the script prompts again for a valid printer index until a valid input is provided by the user.</p>
<p>The second menu is then displayed. An &#8220;if&#8221; statement is used to check if the printer index variable is greater than 0 before the operation to set as the default printer is displayed.</p>
<p>The user is then prompted to enter an operation. Validation for the second menu is done using the same logic as the first menus validation. The difference is an &#8220;if&#8221; statement to check to make sure the operation index supplied is not to set all printers to default.</p>
<pre>
	if ($selectedPrinterIndex -gt 0) {
		$objPrinter = $colPrinters[$selectedPrinterIndex - 1]
	}

	write-host
	switch ($selectedOperationIndex) {
		0 {
			if ($selectedPrinterIndex -eq 0) {
				foreach ($objPrinter in $colPrinters) {
					writePrinterInfo $objPrinter $strComputerName
				}
			}
			else {	writePrinterInfo $objPrinter $strComputerName }
		}
		1 {
			if ($selectedPrinterIndex -eq 0) {
				foreach ($objPrinter in $colPrinters) {
					cancelPrinterJobs $objPrinter
				}
			}
			else {	cancelPrinterJobs $objPrinter }
		}
		2 {
			if ($selectedPrinterIndex -eq 0) {
				foreach ($objPrinter in $colPrinters) {
					pausePrinter $objPrinter
				}
			}
			else {	pausePrinter $objPrinter }
		}
		3 {
			if ($selectedPrinterIndex -eq 0) {
				foreach ($objPrinter in $colPrinters) {
					resumePrinter $objPrinter
				}
			}
			else {	resumePrinter $objPrinter }
		}
		4 {
			if ($selectedPrinterIndex -eq 0) {
				foreach ($objPrinter in $colPrinters) {
					testPrinter $objPrinter
				}
			}
			else {	testPrinter $objPrinter }
		}
		5 {
			setDefaultPrinter $objPrinter
		}
	}
}
while (1)
cls
</pre>
<p>The final section of the script handles performing the selected operation with the selected printer or printers. It starts off by assigning the selected printer object to a variable using the selected printer index if the user did not select all printers.</p>
<p>The control of which operation is to be executed is handled by the Switch cmdlet. Within the curly brackets of the <code>Switch</code> cmdlet the commands executed are the commands within the curly brackets of the number in the <code>Switch</code> cmdlet that match the operation index provided by the user.</p>
<p>In all cases but the last, an if statement is used to check if the selected operation is to be performed on all printers. If all printers have been selected a foreach loop is used to pass all the Printer objects to the proper function otherwise only the Printer object of the selected printer is passed to the function.</p>
<p>The fifth case does not check if all printers were selected because the input validation prevents the option from being able to be selected if all printers are selected. After the switch statement the program’s infinite Do While loop is closed off the screen cleared and execution of the script ends.</p>
<p>Now that you are so familiar with how to create dynamic PowerShell scripts, you probably want to know how to execute a script. To demonstrate, go ahead and copy the commands from all three sections of the script example into notepad and save it to ‘C:\PrinterOperations.ps1’. From PowerShell enter the command below to execute the script.</p>
<pre>
&#038; “C:\PrinterOperations.ps1”
</pre>
<p>With the command above, variable names and functions used in the script will be destroyed when execution completes. If you wish to have script variables and functions available within PowerShell after the script has finished executing you can use dot-sourcing.</p>
<p>The command below will run the script and when execution completes you will have access to the variables and functions created will still be available.</p>
<pre>
&#038; . “C:\PrinterOperations.ps1”
</pre>
<p>I hope that you&#8217;ve enjoyed reading my series on Windows PowerShell.</p>
<p>Keep in mind that there are many additional resources and a number of informative references available on this topic. The owner&#8217;s manual, articles, and many useful scripting examples are available at <a href="http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx">Microsoft TechNet’s Script Center.</a></p>


<h3>Related posts:<ul><li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell-2' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 2'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 2</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell-3' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 3'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 3</a></li>
<li><a href='http://windowsserver.trainsignal.com/windows-server-2008-powershell' rel='bookmark' title='Permanent Link: Take Command of Server 2008 with Windows PowerShell &#8211; Part 1'>Take Command of Server 2008 with Windows PowerShell &#8211; Part 1</a></li>
</ul></h3>]]></content:encoded>
			<wfw:commentRss>http://windowsserver.trainsignal.com/windows-server-2008-powershell-4/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
