Archive

Archive for May, 2013

Fix Problem Where Windows PowerShell Cannot Run Script Whose Path Contains Spaces

May 28th, 2013 4 comments

Most people will likely find the “Run script path with spaces from File Explorer” (to be able to double click a PS script whose path contains spaces to run it) section below the most helpful.  Most of the other content in this post can be found elsewhere, but I provide it for context and completeness.

 

Make running (instead of editing) the default PowerShell script action

The default Windows action when you double click on a PowerShell script is to open it in an editor, rather than to actually run the script.  If this bugs you, it’s easy enough to fix.  Just right-click on the script, go to “Open with” –> “Choose default program…”, and then select Windows PowerShell, making sure the “Use this app for all .ps1 files” option is checked (this might be called “Always use the selected program to open this kind of file” or something else depending on which version of Windows you are using).

ChooseDefaultPowerShellApplication     MakeWindowsPowerShellDefaultApplication

If you don’t mind opening in an editor as the default action, then to run the script you can just right-click on the script and choose “Open with” –> “Windows PowerShell”.  This is probably how 90% of people run their PowerShell scripts; power uses might run their scripts directly from the PowerShell command prompt.

 

Error message when trying to run a script whose path contains spaces

So the problem that the 90% of people are likely to encounter is that as soon as the script path has a space in it (either in the filename itself or in the directory path the file resides in), they will see the powershell console flash some red text at them for about 1/10th of a second before it closes, and they will be wondering why the script did not run; or worse, they won’t know that it didn’t run (see the “Keep PowerShell Console Open” section below).  If they are lucky enough to press Print Screen at the right moment, or decide to open up a PowerShell console and run from there, they might see an error message similar to this:

Powershell Invalid Path Error Message

“The term ‘C:\My’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.”

So the path to the script I was trying to run is "C:\My Folder\My PowerShell Script.ps1", but from the error you can see that it cut the path off at the first space.

 

Run script path with spaces from PowerShell console

So the typical work around for this is to open a PowerShell console and run the script by enclosing the path in double quotes.

Windows 8 Pro Tip: You can open the PowerShell console at your current directory in File Explorer by choosing File –> Open Windows PowerShell.

Open Powershell From File Explorer

If you simply try to run the script by enclosing the path to the script in double quotes you will just see the path spit back at you in the console, instead of actually running the script.

Try to run script with spaces the wrong way

The trick is that you have to put “& “ before the script path to actually run the script.  Also, if you are trying to run a script from the current directory without using the full path, you will need to put “.\” before the relative script filename.

Run PowerShell script the right way

 

Run script path with spaces from File Explorer

So when we are in the PowerShell console we can manually type the path enclosed in double quotes, but what do we do when simply trying to run the file from File Explorer (i.e. Windows Explorer in Windows 7 and previous) by double clicking it? 

The answer: Edit the registry to pass the file path to powershell.exe with the path enclosed in quotes.

The problem is that the “HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command” registry key value looks like this:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"

but we want it to look like this:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""

 

So if you want to go manually edit that key by hand you can, or you can simply download the registry script below and then double click the .reg file to have it update the registry key value for you (choose Yes when asked if you want to continue).

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" \"& \\\"%1\\\"\""

IMHO this seems like a bug with the PowerShell installer (and Windows since PowerShell is built into Windows 7 and up), so please go up-vote the bug I submitted to get this fixed.

So now you can run your PowerShell scripts from File Explorer regardless of whether their path contains spaces or not Smile.  For those interested, this is the post that got me thinking about using the registry to fix this problem.

 

Bonus: Keep PowerShell console open when script is ran from File Explorer

Update – This Bonus section now has its own updated dedicated post here that you should use instead.

When running a script by double-clicking it, if the script completes very quickly the user will see the PowerShell console appear very briefly and then disappear.  If the script gives output that the user wants to see, or if it throws an error, the user won’t have time to read the text.  The typical work around is to open the PowerShell console and manually run the script.  The other option is to adjust our new registry key value a bit.

So to keep the PowerShell console window open after the script completes, we just need to change our new key value to use the –NoExit switch:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" –NoExit "& \"%1\""

And here is the .reg script with the –NoExit switch included:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command]
@="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -NoExit \"& \\\"%1\\\"\""

I hope you find this information as useful as I did.  Happy coding!

Why I Chose WordPress Over Geeks With Blogs, And Moving From WordPress.com To A GoDaddy Hosted Solution

May 17th, 2013 2 comments

A while back I wrote about some reasons why I didn’t like GWB (Geeks With Blogs) and was attracted to WordPress.  6 months later and I am confident that I made the right decision.  GWB was good to me, but their UI and features are just too dated and can’t keep up with what WordPress has to offer.  They said that they had hired some developers to improve the site, but it’s been 6 months and I can’t really see a difference.  When I wrote my last post the one thing that I didn’t like about WordPress.com was that I couldn’t find a theme that would stretch the content area to the full screen width; which is pretty essential for me since a lot of my posts involve long code snippets.  I never did find a theme to do this on WordPress.com (although I gave up after a few hours or searching).  Instead I decided to move to hosting my own WordPress instance.

I have a few other websites that I was hosting on my own personal server at home, but decided to move to GoDaddy for my hosting since they had a half price special and it would cost me less than my power bill to keep my server running (and I already had my domains registered through them).  I opted for the Deluxe package since I have a few websites, and GoDaddy offers up to 25 free WordPress installations with this package, so I have moved my blog from my deadlydog.wordpress.com site to my GoDaddy-hosted blogs.danskingdom.com site.  The migration process should have been painless; just export my deadlydog.wordpress.com site to an xml file (this part was very easy and painless), and then import it into my new blogs.danskingdom.com site.  For some reason when trying to do the import I would often get a “Connection was reset by the server” error.  So it took me probably about 15 tries before it actually imported everything properly; a few times it died half way through the import, but most of the time it would die before the import even started.  Luckily blowing away and recreating an WordPress instance with GoDaddy is easy and only takes about 30 minutes.  Another reason I chose GoDaddy were that their base prices are pretty competitive, plus I consistently receive coupon codes in my email from them for an additional 25% or 30% off (hint, use referral code WOWdeadlyd to get 35% off orders on new products).  Also, their customer service is wonderful.  The support I’ve received via email has been only ok, but anytime I’ve actually called in to their support they’ve been awesome and very helpful.

So once I finally got all of my posts migrated to my own hosted instance I could fix some of the things that annoyed me about my wordpress.com site.  First, I’m able to modify the theme’s css directly without paying anything.  This allowed me to go in and stretch the content area to fit the user’s screen.  You can probably tell while reading this that it isn’t perfect; there is some extra space on the right-hand side, but meh, it’s much better than it was.  Second, it allowed me to add advertisements to my site, which help pay for the hosting costs.  You might be thinking, “What? I don’t see any ads”, but that’s because I’ve placed them at the very bottom of the page to be as non-obtrusive as possible.  Third, it allowed me to hook up Google Analytics to my site so that I can get even more information about my site’s traffic and visitors, and see what search terms were bringing people to my site.  And by hosting my own WordPress instance I can now install any WordPress plugin that I want, instead of only the ones that WordPress.com has allowed.  One thing that I’ve noticed however is that accessing and navigating links on my GoDaddy hosted WordPress site is often slower than it was on WordPress.com.  I’m not sure if this is a temporary thing or what (since I’ve only been hosting with GoDaddy for about a week), but I often notice myself waiting for a webpage to load now, where I never noticed this before with deadlydog.wordpress.com.  However sometimes a page is super quick to load, so it’s not consistent.

One thing that does sort of suck about moving from WordPress.com to my own hosted solution is that I couldn’t figure out how to transfer my site stats across, so my stats for blog.danskingdom.com only start from the day I setup the new blog on that domain.  Another thing that I didn’t realize until after I had setup my new WordPress account was that I would have to pay to have traffic from my old deadlydog.wordpress.com redirected to the new blog.danskingdom.com; it was only $13 for a year though, so that’s not too bad as I’ll likely delete my old wordpress.com site right before that expires.

One other change I had to make when moving from WordPress.com to my own hosted solution was that in order for my code snippets to show up properly I had to install SyntaxHighlighter Evolved on my WordPress instance, which was super simple to do, and I can still use the Source Code Highlighter Plugin for WordPress.com plugin for Windows Live Writer which is great.

GWB users may have noticed that I still post to GWB with a “Read more at” link that points to the post on my new domain (in fact I went and updated all of my old posts to “read more” at my new domain. GWB doesn’t offer any way to forward my blog with them to a different domain (not even a paid solution like WordPress.com), so updating my old posts with a link to my new domain was the best I could do).  This is because the one and only thing that I’ll miss about GWB is the community.  While double posting (bad I know, but at least I’ve switched to the “Read more at” method rather than double posting the entire post) I found that I would still get more comments on my GWB posts than my WordPress posts.  Did this mean that my GWB posts were getting more traffic though? I can’t tell because GWB doesn’t offer any sort of information or stats about how many visits my site receives, and I can’t hook up Google Analytics or other 3rd party services to it either.  I’m going to continue double posting with the “Read more at” links so that GWB users can still see my post titles on their feeds and don’t miss out on anything I post that they might find useful, as I too often monitor the GWB main page feed to see other code-related posts that I don’t want to miss out on.  Also, by changing to using the “Read more at” convention it allows me to only have to update my one website when I update an old blog post, rather than having to update multiple; this was a major pain point, especially when I needed to use different Windows Live Writer (WLW) plugins depending on which site I was posting code to.

Anyways, these are my thoughts on my blog’s move.  Hopefully it helps you with making a decision about going with GWB or maintaining your own hosted WordPress solution, and whether you choose GoDaddy or not.  Again, use referral code WOWdeadlyd to get 35% off your GoDaddy order.

Powershell functions to get an xml node, and get and set an xml element’s value, even when the element does not already exist

May 16th, 2013 17 comments

I’m new to working with Xml through PowerShell and was so impressed when I discovered how easy it was to read an xml element’s value.  I’m working with reading/writing .nuspec files for working with NuGet.  Here’s a sample xml of a .nuspec xml file:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>MyAppsId</id>
    <version>1.0.1</version>
    <title>MyApp</title>
    <authors>Daniel Schroeder</authors>
    <owners>Daniel Schroeder</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>My App.</description>
    <summary>My App.</summary>
    <tags>Powershell, Application</tags>
  </metadata>
  <files>
    <file src="MyApp.ps1" target="content\MyApp.ps1" />
  </files>
</package>

 

In PowerShell if I want to get the version element’s value, I can just do:

# Read in the file contents and return the version node's value.
[ xml ]$fileContents = Get-Content -Path $NuSpecFilePath
return $fileContents.package.metadata.version

 

Wow, that’s super easy.  And if I want to update that version number, I can just do:

# Read in the file contents, update the version node's value, and save the file.
[ xml ] $fileContents = Get-Content -Path $NuSpecFilePath
$fileContents.package.metadata.version = $NewVersionNumber
$fileContents.Save($NuSpecFilePath)

 

Holy smokes. So simple it blows my mind.  So everything is great, right?  Well, it is until you try and read or write to an element that doesn’t exist.  If the <version> element is not in the xml, when I try and read from it or write to it, I get an error such as “Error: Property ‘version’ cannot be found on this object. Make sure that it exists.”.  You would think that checking if an element exists would be straight-forward and easy right? Well, it almost is.  There’s a SelectSingleNode() function that we can use to look for the element, but what I realized after a couple hours of banging my head on the wall and stumbling across this stack overflow post, is that in order for this function to work properly, you really need to use the overloaded method that also takes an XmlNamespaceManager; otherwise the SelectSingleNode() function always returns null.

So basically you need an extra 2 lines in order to setup an XmlNamespaceManager every time you need to look for a node.  This is a little painful, so instead I created this function that will get you the node if it exists, and return $null if it doesn’t:

function Get-XmlNode([ xml ]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	# If a Namespace URI was not given, use the Xml document's default namespace.
	if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $XmlDocument.DocumentElement.NamespaceURI }	
	
	# In order for SelectSingleNode() to actually work, we need to use the fully qualified node path along with an Xml Namespace Manager, so set them up.
	$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($XmlDocument.NameTable)
	$xmlNsManager.AddNamespace("ns", $NamespaceURI)
	$fullyQualifiedNodePath = "/ns:$($NodePath.Replace($($NodeSeparatorCharacter), '/ns:'))"
	
	# Try and get the node, then return it. Returns $null if the node was not found.
	$node = $XmlDocument.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager)
	return $node
}

 

And you would call this function like so:

# Read in the file contents and return the version node's value.
[ xml ]$fileContents = Get-Content -Path $NuSpecFilePath
$node = Get-XmlNode -XmlDocument $fileContents -NodePath "package.metadata.version"
if ($node -eq $null) { return $null }
return $fileContents.package.metadata.version

 

So if the node doesn’t exist (i.e. is $null), I return $null instead of trying to access the non-existent element.

So by default this Get-XmlNode function uses the xml’s root namespace, which is what we want 95% of the time.  It also takes a NodeSeparatorCharacter that defaults to a period.  While Googling for answers I saw that many people use the the syntax “$fileContents/package/metadata/version” instead of “$fileContents.package.metadata.version”.  I prefer the dot notation, but for those who like the slash just override the NodeSeparatorCharacter with a slash.

<Update>

Later I found that I also wanted the ability to return back multiple xml nodes; that is, if multiple “version” elements were defined I wanted to get them all, not just the first one.  This is simple; instead of using .SelectSingleNode() we can use .SelectNodes().  In order to avoid duplicating code, I broke the code to get the Xml Namespace Manager and Fully Qualified Node Path out into their own functions.  Here is the rewritten code, with the new Get-XmlNodes function:

function Get-XmlNamespaceManager([ xml ]$XmlDocument, [string]$NamespaceURI = "")
{
    # If a Namespace URI was not given, use the Xml document's default namespace.
	if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $XmlDocument.DocumentElement.NamespaceURI }	
	
	# In order for SelectSingleNode() to actually work, we need to use the fully qualified node path along with an Xml Namespace Manager, so set them up.
	[System.Xml.XmlNamespaceManager]$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($XmlDocument.NameTable)
	$xmlNsManager.AddNamespace("ns", $NamespaceURI)
    return ,$xmlNsManager		# Need to put the comma before the variable name so that PowerShell doesn't convert it into an Object[].
}

function Get-FullyQualifiedXmlNodePath([string]$NodePath, [string]$NodeSeparatorCharacter = '.')
{
    return "/ns:$($NodePath.Replace($($NodeSeparatorCharacter), '/ns:'))"
}

function Get-XmlNode([ xml ]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	$xmlNsManager = Get-XmlNamespaceManager -XmlDocument $XmlDocument -NamespaceURI $NamespaceURI
	[string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter
	
	# Try and get the node, then return it. Returns $null if the node was not found.
	$node = $XmlDocument.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager)
	return $node
}

function Get-XmlNodes([ xml ]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	$xmlNsManager = Get-XmlNamespaceManager -XmlDocument $XmlDocument -NamespaceURI $NamespaceURI
	[string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter

	# Try and get the nodes, then return them. Returns $null if no nodes were found.
	$nodes = $XmlDocument.SelectNodes($fullyQualifiedNodePath, $xmlNsManager)
	return $nodes
}

Note the comma in the return statement of the Get-XmlNamespaceManager function.  It took me a while to discover why things broke without it.

</Update>

So once I had this, I decided that I might as well make functions for easily getting and setting the text values of an xml element, which is what is provided here:

function Get-XmlElementsTextValue([ xml ]$XmlDocument, [string]$ElementPath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	# Try and get the node.	
	$node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter
	
	# If the node already exists, return its value, otherwise return null.
	if ($node) { return $node.InnerText } else { return $null }
}

function Set-XmlElementsTextValue([ xml ]$XmlDocument, [string]$ElementPath, [string]$TextValue, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	# Try and get the node.	
	$node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter
	
	# If the node already exists, update its value.
	if ($node)
	{ 
		$node.InnerText = $TextValue
	}
	# Else the node doesn't exist yet, so create it with the given value.
	else
	{
		# Create the new element with the given value.
		$elementName = $ElementPath.SubString($ElementPath.LastIndexOf($NodeSeparatorCharacter) + 1)
 		$element = $XmlDocument.CreateElement($elementName, $XmlDocument.DocumentElement.NamespaceURI)		
		$textNode = $XmlDocument.CreateTextNode($TextValue)
		$element.AppendChild($textNode) > $null
		
		# Try and get the parent node.
		$parentNodePath = $ElementPath.SubString(0, $ElementPath.LastIndexOf($NodeSeparatorCharacter))
		$parentNode = Get-XmlNode -XmlDocument $XmlDocument -NodePath $parentNodePath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter
		
		if ($parentNode)
		{
			$parentNode.AppendChild($element) > $null
		}
		else
		{
			throw "$parentNodePath does not exist in the xml."
		}
	}
}

 

The Get-XmlElementsTextValue function is pretty straight forward; return the value if it exists, otherwise return null.  The Set-XmlElementsTextValue is a little more involved because if the element does not exist already, we need to create the new element and attach it as a child to the parent element.

Here’s an example of calling Get-XmlElementsTextValue:

# Read in the file contents and return the version element's value.
[ xml ]$fileContents = Get-Content -Path $NuSpecFilePath
return Get-XmlElementsTextValue -XmlDocument $fileContents -ElementPath "package.metadata.version"

 

And an example of calling Set-XmlElementsTextValue:

# Read in the file contents, update the version element's value, and save the file.
[ xml ]$fileContents = Get-Content -Path $NuSpecFilePath
Set-XmlElementsTextValue -XmlDocument $fileContents -ElementPath "package.metadata.version" -TextValue $NewVersionNumber
$fileContents.Save($NuSpecFilePath)

 

Note that these 2 functions depend on the Get-XmlNode function provided above.

<Update2 – January 7, 2016>

I have had multiple people ask me for similar functions for getting and setting an element’s Attribute value as well, so here are the corresponding functions for that:

function Get-XmlElementsAttributeValue([ xml ]$XmlDocument, [string]$ElementPath, [string]$AttributeName, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	# Try and get the node. 
	$node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter
	
	# If the node and attribute already exist, return the attribute's value, otherwise return null.
	if ($node -and $node.$AttributeName) { return $node.$AttributeName } else { return $null }
}

function Set-XmlElementsAttributeValue([ xml ]$XmlDocument, [string]$ElementPath, [string]$AttributeName, [string]$AttributeValue, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.')
{
	# Try and get the node. 
	$node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter
	
	# If the node already exists, create/update its attribute's value.
	if ($node)
	{ 
		$attribute = $XmlDocument.CreateNode([System.Xml.XmlNodeType]::Attribute, $AttributeName, $NamespaceURI)
		$attribute.Value = $AttributeValue
		$node.Attributes.SetNamedItem($attribute) > $null
	}
	# Else the node doesn't exist yet, so create it with the given attribute value.
	else
	{
		# Create the new element with the given value.
		$elementName = $ElementPath.SubString($ElementPath.LastIndexOf($NodeSeparatorCharacter) + 1)
		$element = $XmlDocument.CreateElement($elementName, $XmlDocument.DocumentElement.NamespaceURI)
		$element.SetAttribute($AttributeName, $NamespaceURI, $AttributeValue) > $null
		
		# Try and get the parent node.
		$parentNodePath = $ElementPath.SubString(0, $ElementPath.LastIndexOf($NodeSeparatorCharacter))
		$parentNode = Get-XmlNode -XmlDocument $XmlDocument -NodePath $parentNodePath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter
		
		if ($parentNode)
		{
			$parentNode.AppendChild($element) > $null
		}
		else
		{
			throw "$parentNodePath does not exist in the xml."
		}
	}
}

</Update2>

Rather than copy-pasting, you can download all of the functions shown here.

I hope you find this useful and that it saves you some time.  Happy coding!

PowerShell function to create a password protected zip file

May 9th, 2013 3 comments

There are a few different ways to create zip files in powershell, but not many that allow you to create one that is password protected.  I found this post that shows how to do it using 7zip, so I thought I would share my modified solution.

Here is the function I wrote that uses 7zip to perform the zip, since 7zip supports using a password to zip the files.  This script looks for the 7zip executable (7z.exe) in the default install locations, and if not found it will use the stand-alone 7zip executable (7za.exe) if it is in the same directory as the powershell script.

Updated function to support multiple compression types: 7z, zip, gzip, bzip2, tar, iso, and udf.

function Write-ZipUsing7Zip([string]$FilesToZip, [string]$ZipOutputFilePath, [string]$Password, [ValidateSet('7z','zip','gzip','bzip2','tar','iso','udf')][string]$CompressionType = 'zip', [switch]$HideWindow)
{
	# Look for the 7zip executable.
	$pathTo32Bit7Zip = "C:\Program Files (x86)\7-Zip\7z.exe"
	$pathTo64Bit7Zip = "C:\Program Files\7-Zip\7z.exe"
	$THIS_SCRIPTS_DIRECTORY = Split-Path $script:MyInvocation.MyCommand.Path
	$pathToStandAloneExe = Join-Path $THIS_SCRIPTS_DIRECTORY "7za.exe"
	if (Test-Path $pathTo64Bit7Zip) { $pathTo7ZipExe = $pathTo64Bit7Zip } 
	elseif (Test-Path $pathTo32Bit7Zip) { $pathTo7ZipExe = $pathTo32Bit7Zip }
	elseif (Test-Path $pathToStandAloneExe) { $pathTo7ZipExe = $pathToStandAloneExe }
	else { throw "Could not find the 7-zip executable." }
	
	# Delete the destination zip file if it already exists (i.e. overwrite it).
	if (Test-Path $ZipOutputFilePath) { Remove-Item $ZipOutputFilePath -Force }
	
	$windowStyle = "Normal"
	if ($HideWindow) { $windowStyle = "Hidden" }
	
	# Create the arguments to use to zip up the files.
	# Command-line argument syntax can be found at: http://www.dotnetperls.com/7-zip-examples
	$arguments = "a -t$CompressionType ""$ZipOutputFilePath"" ""$FilesToZip"" -mx9"
	if (!([string]::IsNullOrEmpty($Password))) { $arguments += " -p$Password" }
	
	# Zip up the files.
	$p = Start-Process $pathTo7ZipExe -ArgumentList $arguments -Wait -PassThru -WindowStyle $windowStyle

	# If the files were not zipped successfully.
	if (!(($p.HasExited -eq $true) -and ($p.ExitCode -eq 0))) 
	{
		throw "There was a problem creating the zip file '$ZipFilePath'."
	}
}

And here’s some examples of how to call the function:

Write-ZipUsing7Zip -FilesToZip "C:\SomeFolder" -ZipOutputFilePath "C:\SomeFolder.zip" -Password "password123"
Write-ZipUsing7Zip "C:\Folder\*.txt" "C:\FoldersTxtFiles.zip" -HideWindow

 

I hope you find this useful.

Happy coding!

PowerShell Multi-Line Input Box Dialog, Open File Dialog, Folder Browser Dialog, Input Box, and Message Box

May 1st, 2013 37 comments

Updated May 17, 2013 to fix potential bug and add more parameters to some functions.

Updated Dec 5, 2013 to release COM object from Read-FolderBrowserDialog function.

I love PowerShell, and when prompting users for input I often prefer to use GUI controls rather than have them enter everything into the console, as some things like browsing for files or folders or entering multi-line text aren’t very pleasing to do directly in the PowerShell prompt window.  So I thought I’d share some PowerShell code that I often use for these purposes.  Below I give the code for creating each type of GUI control from a function, an example of calling the function, and a screen shot of what the resulting GUI control looks like.

Show a message box

Function:

# Show message box popup and return the button clicked by the user.
function Read-MessageBoxDialog([string]$Message, [string]$WindowTitle, [System.Windows.Forms.MessageBoxButtons]$Buttons = [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]$Icon = [System.Windows.Forms.MessageBoxIcon]::None)
{
	Add-Type -AssemblyName System.Windows.Forms
	return [System.Windows.Forms.MessageBox]::Show($Message, $WindowTitle, $Buttons, $Icon)
}

Example:

$buttonClicked = Read-MessageBoxDialog -Message "Please press the OK button." -WindowTitle "Message Box Example" -Buttons OKCancel -Icon Exclamation
if ($buttonClicked -eq "OK") { Write-Host "Thanks for pressing OK" }
else { Write-Host "You clicked $buttonClicked" }

Message Box Example

 

Prompt for single-line user input

Function:

# Show input box popup and return the value entered by the user.
function Read-InputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{
	Add-Type -AssemblyName Microsoft.VisualBasic
	return [Microsoft.VisualBasic.Interaction]::InputBox($Message, $WindowTitle, $DefaultText)
}

Example:

$textEntered = Read-InputBoxDialog -Message "Please enter the word 'Banana'" -WindowTitle "Input Box Example" -DefaultText "Apple"
if ($textEntered -eq $null) { Write-Host "You clicked Cancel" }
elseif ($textEntered -eq "Banana") { Write-Host "Thanks for typing Banana" }
else { Write-Host "You entered $textEntered" }

Input Box Example

 

Prompt for a file (based on a post the Scripting Guy made)

Function:

# Show an Open File Dialog and return the file selected by the user.
function Read-OpenFileDialog([string]$WindowTitle, [string]$InitialDirectory, [string]$Filter = "All files (*.*)|*.*", [switch]$AllowMultiSelect)
{  
	Add-Type -AssemblyName System.Windows.Forms
	$openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
	$openFileDialog.Title = $WindowTitle
	if (![string]::IsNullOrWhiteSpace($InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory }
	$openFileDialog.Filter = $Filter
	if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true }
	$openFileDialog.ShowHelp = $true	# Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE.
	$openFileDialog.ShowDialog() > $null
	if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename }
}

Example:

$filePath = Read-OpenFileDialog -WindowTitle "Select Text File Example" -InitialDirectory 'C:\' -Filter "Text files (*.txt)|*.txt"
if (![string]::IsNullOrEmpty($filePath)) { Write-Host "You selected the file: $filePath" }
else { "You did not select a file." }

Select Text File Example

 

Prompt for a directory (based on this post, as using System.Windows.Forms.FolderBrowserDialog may hang depending on system configuration and running from the console vs. PS ISE)

Function:

# Show an Open Folder Dialog and return the directory selected by the user.
function Read-FolderBrowserDialog([string]$Message, [string]$InitialDirectory, [switch]$NoNewFolderButton)
{
    $browseForFolderOptions = 0
    if ($NoNewFolderButton) { $browseForFolderOptions += 512 }

	$app = New-Object -ComObject Shell.Application
	$folder = $app.BrowseForFolder(0, $Message, $browseForFolderOptions, $InitialDirectory)
	if ($folder) { $selectedDirectory = $folder.Self.Path } else { $selectedDirectory = '' }
	[System.Runtime.Interopservices.Marshal]::ReleaseComObject($app) > $null
	return $selectedDirectory
}

Example:

$directoryPath = Read-FolderBrowserDialog -Message "Please select a directory" -InitialDirectory 'C:\' -NoNewFolderButton
if (![string]::IsNullOrEmpty($directoryPath)) { Write-Host "You selected the directory: $directoryPath" }
else { "You did not select a directory." }

Browse For Folder

 

Prompt for multi-line user input (based on code shown in this TechNet article)

Function:

function Read-MultiLineInputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{
<#
	.SYNOPSIS
	Prompts the user with a multi-line input box and returns the text they enter, or null if they cancelled the prompt.
	
	.DESCRIPTION
	Prompts the user with a multi-line input box and returns the text they enter, or null if they cancelled the prompt.
	
	.PARAMETER Message
	The message to display to the user explaining what text we are asking them to enter.
	
	.PARAMETER WindowTitle
	The text to display on the prompt window's title.
	
	.PARAMETER DefaultText
	The default text to show in the input box.
	
	.EXAMPLE
	$userText = Read-MultiLineInputDialog "Input some text please:" "Get User's Input"
	
	Shows how to create a simple prompt to get mutli-line input from a user.
	
	.EXAMPLE
	# Setup the default multi-line address to fill the input box with.
	$defaultAddress = @'
	John Doe
	123 St.
	Some Town, SK, Canada
	A1B 2C3
	'@
	
	$address = Read-MultiLineInputDialog "Please enter your full address, including name, street, city, and postal code:" "Get User's Address" $defaultAddress
	if ($address -eq $null)
	{
		Write-Error "You pressed the Cancel button on the multi-line input box."
	}
	
	Prompts the user for their address and stores it in a variable, pre-filling the input box with a default multi-line address.
	If the user pressed the Cancel button an error is written to the console.
	
	.EXAMPLE
	$inputText = Read-MultiLineInputDialog -Message "If you have a really long message you can break it apart`nover two lines with the powershell newline character:" -WindowTitle "Window Title" -DefaultText "Default text for the input box."
	
	Shows how to break the second parameter (Message) up onto two lines using the powershell newline character (`n).
	If you break the message up into more than two lines the extra lines will be hidden behind or show ontop of the TextBox.
	
	.NOTES
	Name: Show-MultiLineInputDialog
	Author: Daniel Schroeder (originally based on the code shown at http://technet.microsoft.com/en-us/library/ff730941.aspx)
	Version: 1.0
#>
	Add-Type -AssemblyName System.Drawing
	Add-Type -AssemblyName System.Windows.Forms
	
	# Create the Label.
	$label = New-Object System.Windows.Forms.Label
	$label.Location = New-Object System.Drawing.Size(10,10) 
	$label.Size = New-Object System.Drawing.Size(280,20)
	$label.AutoSize = $true
	$label.Text = $Message
	
	# Create the TextBox used to capture the user's text.
	$textBox = New-Object System.Windows.Forms.TextBox 
	$textBox.Location = New-Object System.Drawing.Size(10,40) 
	$textBox.Size = New-Object System.Drawing.Size(575,200)
	$textBox.AcceptsReturn = $true
	$textBox.AcceptsTab = $false
	$textBox.Multiline = $true
	$textBox.ScrollBars = 'Both'
	$textBox.Text = $DefaultText
	
	# Create the OK button.
	$okButton = New-Object System.Windows.Forms.Button
	$okButton.Location = New-Object System.Drawing.Size(415,250)
	$okButton.Size = New-Object System.Drawing.Size(75,25)
	$okButton.Text = "OK"
	$okButton.Add_Click({ $form.Tag = $textBox.Text; $form.Close() })
	
	# Create the Cancel button.
	$cancelButton = New-Object System.Windows.Forms.Button
	$cancelButton.Location = New-Object System.Drawing.Size(510,250)
	$cancelButton.Size = New-Object System.Drawing.Size(75,25)
	$cancelButton.Text = "Cancel"
	$cancelButton.Add_Click({ $form.Tag = $null; $form.Close() })
	
	# Create the form.
	$form = New-Object System.Windows.Forms.Form 
	$form.Text = $WindowTitle
	$form.Size = New-Object System.Drawing.Size(610,320)
	$form.FormBorderStyle = 'FixedSingle'
	$form.StartPosition = "CenterScreen"
	$form.AutoSizeMode = 'GrowAndShrink'
	$form.Topmost = $True
	$form.AcceptButton = $okButton
	$form.CancelButton = $cancelButton
	$form.ShowInTaskbar = $true
	
	# Add all of the controls to the form.
	$form.Controls.Add($label)
	$form.Controls.Add($textBox)
	$form.Controls.Add($okButton)
	$form.Controls.Add($cancelButton)
	
	# Initialize and show the form.
	$form.Add_Shown({$form.Activate()})
	$form.ShowDialog() > $null	# Trash the text of the button that was clicked.
	
	# Return the text that the user entered.
	return $form.Tag
}

Example:

$multiLineText = Read-MultiLineInputBoxDialog -Message "Please enter some text. It can be multiple lines" -WindowTitle "Multi Line Example" -DefaultText "Enter some text here..."
if ($multiLineText -eq $null) { Write-Host "You clicked Cancel" }
else { Write-Host "You entered the following text: $multiLineText" }

Multi Line Example

 

All of these but the multi-line input box just use existing Windows Forms / Visual Basic controls.

I originally was using the Get verb to prefix the functions, then switched to the Show verb, but after reading through this page, I decided that the Read verb is probably the most appropriate (and it lines up with the Read-Host cmdlet).

Hopefully you find this useful.

Happy coding!