Scripting Games 2012 comments: #7 update on beginners event 3

It was bugging me that I couldn’t get try-catch work on the folder where I didn’t have permissions. Finally thought of the reason – set the ErrorAction to Ignore. Heres the revised script

[CmdletBinding()]            
param (            
 [string]$path = "C:\2012sg\event3",            
 [string]$file = "Process3.txt"            
)            
            
Write-Verbose "Test path is valid"            
if (-not (Test-Path -Path $path -IsValid)){            
  Throw "Invalid path $path"            
}            
            
if (-not (Test-Path -Path $path)){            
   Write-Verbose "Create Folder"            
   try {            
     $rt = New-Item -Path $path -ItemType Directory -ErrorAction Ignore            
   }            
   catch {            
     $path = (Join-Path -Path $env:HOMEDRIVE -ChildPath $env:HOMEPATH) + (Split-Path -Path $path -NoQualifier)            
                 
     Write-Debug $path            
     New-Item -Path $path -ItemType Directory | Out-Null            
   }            
}            
            
Write-Verbose "Write Process data"            
Get-Process |             
Format-Table Name, Id  -a |             
Out-File -FilePath (Join-Path -Path $path -ChildPath $file)            
            
<# 
.SYNOPSIS
Creates a folder to hold a file containing process data

.DESCRIPTION
A folder - by default "C:\2012sg\event3" - is created and a file called
"Process3.txt" by default is created holding process data. The process 
name and id is used to fill the file. 

Any existing file is over written

If the folder can't be created in the root of C: it is created in
$env:HOMEDRIVE\$env:HOMEPATH i.e. the users home drive

.PARAMETER  path

Path of the folder we want to create
Default is "C:\2012sg\event3"

.PARAMETER  file

File name of file to hold process data
Default is "Process3.txt"

.EXAMPLE
.\beg3.ps1

Runs script with default values

.EXAMPLE
.\beg3.ps1 -path "c:\testbeg3\event3" -file "testP3.txt"

Runs script with values for path and file supplied

.EXAMPLE
.\beg3.ps1 -Verbose

Runs script with verbose output

#>
Advertisements
This entry was posted in Powershell Basics, Scripting. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s