2012 Scripting Games Commentary: Lose the Copy and Paste (and other suggestions)

I'm going to share a modified entry from this year's scripting games:

$Path = "C:\2012SG\eventX"
 
if (Test-Path $Path)
{
    Write-host $Path " is present"
    Get-Service | Select Name, Status | Out-File $Path + serviceX.txt
}
else
{
    New-Item -Path $Path -type directory
    Get-Service | Select Name, Status | Out-File $Path + serviceX.txt
}

Can anyone guess what I'm about to whine about? See that duplicated command? No reason for it. Here's a better version:

[CmdletBinding()]
Param($Path
= "C:\2012SG\eventX\",$file="output.txt")
 
if (Test-Path $Path)
{
    Write-Verbose "$Path is present"
}
else
{
       Write-Verbose "Creating $path"
    New-Item -Path $Path -type directory

Get-Service | Select Name,Status | Out-File "$Path\$file"

Here's what I did, and why:

 

  • I parameterized $Path. If you've already taken the trouble to put something in a variable, why not expose that to someone running the script? And, by the way, why not put the whole filename in there so it's easily changeable? The incremental effort needed to turn that into a parameter is practically nil.
  • I moved the command out of the If construct. If it's going to run either way, then it doesn't belong in the conditional portion of the code. Put it after.
  • I changed Write-Host to Write-Verbose. Grrrr. I added [CmdletBinding()] so that the script can be run with -verbose to enable that output if desired. 
  • I'm pretty sure the original Out-File won't work, because $path doesn't have a \ at the end of it, and the script is making a folder with a filename, basically. And, I hate string concatenation regardless. And by putting the path and filename into the $path variable parameter, I took that burden off myself as a script author. Yay, me!

 


Posted Apr 09 2012, 04:48 PM by Don Jones
Copyright 2012 PowerShell.com. All rights reserved.