PowerShell for Windows Admins

Apr 13 2012   3:38PM GMT

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

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

#>

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: