?
SolvedPrivate

powershell try catch  and $ErrorActionPreference = continue

Posted on 2017-04-18
6
Medium Priority
?
86 Views
Last Modified: 2017-04-18
Hi all,

I need to know how try catch it work  with $ErrorActionPreference = continue.
I have foreach structure into  try {} catch{} block , but when exception occurs the script stop immediately (at first exception).
However I begin my code with $ErrorActionPreference = continue.

Can you explain me how work try catch with $ErrorActionPreference = continue  and explain me how to   make sure that script will continue at next line of CSV file ?



the code :
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
$PWDexp = $true
$PWDmod = $false
$OU = "OU=FTP_account,OU=PJA,DC=ASSO,DC=local"
$file = "D:\FTP\Provisionning\NewFtpUsers.csv"
$ftp2 = "SVRFTP-021v.ASSO.local"
$ErrorActionPreference = 'Continue'

	try 
	{

    
	Import-Module ActiveDirectory
	Import-Module WebAdministration #  Module d'administrattion IIS
	Import-Module NTFSSecurity		#  Module de gestion des ACL FileSystem 	 

	  #parsing du fichier csv 
	  Import-Csv $file -Delimiter ";" | % {
		
        $user= Get-ADUser -Filter { SamAccountName -eq "$($_.Login)" }
        Write-Output $user
		
	    if (-not $user)
		{
		
		# build des comptes AD pour user ftp
		 New-ADUser -Name $_.FullName `
		-Path $OU `
		-SamAccountName $_.Login `
		-AccountPassword (ConvertTo-SecureString $_.Key  -AsPlainText -force)`
		-PasswordNeverExpires:$PWDexp `
		-CannotChangePassword:$PWDmod `
		-Description $_.info `
		-Enabled:$True
		
		}
		
		$BuildPath = "$($_.Path)\$($_.Login)" # Construction du chemin physique
        $Identity = $($_.Login)
        Write-host $Identity
       

		
		if (-not  (Test-Path $($BuildPath)))
		{
		
        # Config Dossier physique + ACL NTFS
		New-Item $BuildPath -itemType directory 
        Get-Item $BuildPath | Set-NTFSOwner -Account BUILTIN\Administrators
		Get-Item $BuildPath | Add-NTFSACCESS -Account ASSO\"$Identity" -AccessRights Modify

        # Config Dossier FTP + ACL FTP SUR SVRFTP-020V
		New-Item IIS:\Sites\FTP\ASSO\"$Identity" -Type VirtualDirectory -PhysicalPath $BuildPath 
		Add-WebConfiguration -Filter /System.FtpServer/Security/Authorization -Value (@{AccessType="Allow";  `
		Users="ASSO\$Identity"; Permissions=3}) -PSPath IIS: -Location "FTP/ASSO/$Identity"

        # Config Dossier FTP + ACL FTP SUR SVRFTP-021V
        Invoke-Command -ComputerName $ftp2 -ScriptBlock { 
        
                param($Identity,$BuildPath)

                $ErrorActionPreference = 'Continue'
                
                Try 
                {
                    Set-ExecutionPolicy -ExecutionPolicy AllSigned
                    Import-Module WebAdministration
                    New-Item IIS:\Sites\FTP\ASSO\"$Identity" -Type VirtualDirectory -PhysicalPath $BuildPath 
		            Add-WebConfiguration -Filter /System.FtpServer/Security/Authorization -Value (@{AccessType="Allow";  `
		            Users="ASSO\$Identity"; Permissions=3}) -PSPath IIS: -Location "FTP/ASSO/$Identity"

                }
                catch  [System.Net.WebException] 
                {
                      
                    Write-output $_.InvocationInfo.ScriptLineNumber
	                Write-output $_.Exception.Message
	                Write-output $_.Exception.ItemName
                    Write-output $_.ErrorDetails.Message
                    Write-output $_.InvocationInfo.PositionMessage
                    

                }

        
            } -ArgumentList $Identity,$BuildPath



		}

	  }

	}
    catch [System.Net.WebException] 
    {
      
      Write-output $_.InvocationInfo.ScriptLineNumber
	  Write-output $_.Exception.Message
	  Write-output $_.Exception.ItemName
      Write-output $_.ErrorDetails.Message
      Write-output $_.InvocationInfo.PositionMessage
      

    }
    catch [System.IO.IOException]
    {

      Write-output $_.InvocationInfo.ScriptLineNumber
	  Write-output $_.Exception.Message
	  Write-output $_.Exception.ItemName
      Write-output $_.ErrorDetails.Message
      Write-output $_.InvocationInfo.PositionMessage
        
    }

Open in new window


Thank you
0
Comment
Question by:0rwell
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 71

Expert Comment

by:Chris Dent
ID: 42097403
ErrorAction Stop turns all non-terminating errors into terminating errors. That'll be errors raised by PowerShell commands since nothing else raises non-terminating errors.

You're handling a very limited set of exception types. What error is being thrown?
0
 
LVL 71

Assisted Solution

by:Chris Dent
Chris Dent earned 1000 total points
ID: 42097415
By the way, this includes hard termination if you have an unhandled exception anywhere, including within the remotely executed script block.
0
 
LVL 85

Accepted Solution

by:
oBdA earned 1000 total points
ID: 42097433
In short (there is an abundance of sites explaining this in detail), there are two kinds of errors in PS: terminating (which throw an exception - can only be caught with Try/Catch) and non-terminating (which will only set $? to $false, and can not be caught with Try/Catch). A non-terminating error can be turned into a terminating one by using "-ErrorAction Stop" or setting the Preference accordingly. It does not work the other way around. Which kind of error a cmdlet produces is up to the cmdlet and the error situation.
You currently have a Try/Catch block around the whole "ForEach" loop, so any terminating error in this loop will immediately stop all processing. To be able to continue with the csv, you need to move the Try/Catch inside the ForEach loop.
Try it like this, for example:
$PWDexp = $true
$PWDmod = $false
$OU = "OU=FTP_account,OU=PJA,DC=ASSO,DC=local"
$file = "D:\FTP\Provisionning\NewFtpUsers.csv"
$ftp2 = "SVRFTP-021v.ASSO.local"
$ErrorActionPreference = 'Stop'

Import-Module ActiveDirectory
Import-Module WebAdministration	#  Module d'administrattion IIS
Import-Module NTFSSecurity		#  Module de gestion des ACL FileSystem 	 

#parsing du fichier csv 
Import-Csv $file -Delimiter ";" | ForEach-Object {
	Try {
		$user = Get-ADUser -Filter {SamAccountName -eq "$($_.Login)"}
		Write-Output $user
		If (-not $user) {
			# build des comptes AD pour user ftp
			New-ADUser -Name $_.FullName `
				-Path $OU `
				-SamAccountName $_.Login `
				-AccountPassword (ConvertTo-SecureString $_.Key -AsPlainText -Force) `
				-PasswordNeverExpires:$PWDexp `
				-CannotChangePassword:$PWDmod `
				-Description $_.info `
				-Enabled:$True
		}
		
		$BuildPath = "$($_.Path)\$($_.Login)" # Construction du chemin physique
		$Identity = $($_.Login)
		Write-Host $Identity

		If (-not (Test-Path -Path $BuildPath)) {
			# Config Dossier physique + ACL NTFS
			New-Item $BuildPath -ItemType Directory 
			Get-Item $BuildPath | Set-NTFSOwner -Account BUILTIN\Administrators
			Get-Item $BuildPath | Add-NTFSACCESS -Account ASSO\"$Identity" -AccessRights Modify

			# Config Dossier FTP + ACL FTP SUR SVRFTP-020V
			New-Item IIS:\Sites\FTP\ASSO\"$Identity" -Type VirtualDirectory -PhysicalPath $BuildPath 
			Add-WebConfiguration -Filter /System.FtpServer/Security/Authorization -Value (@{AccessType="Allow"; Users="ASSO\$Identity"; Permissions=3}) -PSPath IIS: -Location "FTP/ASSO/$Identity"
		}
		
		# Config Dossier FTP + ACL FTP SUR SVRFTP-021V
		Invoke-Command -ComputerName $ftp2 -ArgumentList $Identity, $BuildPath -ScriptBlock { 
			Param($Identity, $BuildPath)
			$ErrorActionPreference = 'Stop'
			If (-not (Test-Path -Path $BuildPath)) {
				Try {
					Import-Module WebAdministration
					New-Item IIS:\Sites\FTP\ASSO\"$Identity" -Type VirtualDirectory -PhysicalPath $BuildPath 
					Add-WebConfiguration -Filter /System.FtpServer/Security/Authorization -Value (@{AccessType="Allow"; Users="ASSO\$Identity"; Permissions=3}) -PSPath IIS: -Location "FTP/ASSO/$Identity"
				} Catch {
					Write-Output $_.InvocationInfo.ScriptLineNumber
					Write-Output $_.Exception.Message
					Write-Output $_.Exception.ItemName
					Write-Output $_.ErrorDetails.Message
					Write-Output $_.InvocationInfo.PositionMessage
				}
			}
		}
	} Catch {
		Write-Output $_.InvocationInfo.ScriptLineNumber
		Write-Output $_.Exception.Message
		Write-Output $_.Exception.ItemName
		Write-Output $_.ErrorDetails.Message
		Write-Output $_.InvocationInfo.PositionMessage
	}
}

Open in new window

0
Understanding Linux Permissions

Linux for beginners: How to view the permissions associated with files and directories and also how you can change them.

 

Author Closing Comment

by:0rwell
ID: 42097761
Thanks, it's more explicit.
0
 

Author Comment

by:0rwell
ID: 42097791
@Chris Dent
I just wanted to catch IIS and Filesystem errors
0
 
LVL 71

Expert Comment

by:Chris Dent
ID: 42097844
Sure, but you have to appreciate that setting ErrorAction to Stop kills a script if *any* unhandled error is thrown (it doesn't just ignore everything except those you catch).

The tweak oBdA has shown fixes the immediate problem, moving the scope of your try / catch inside the loop changes the scope of the error handling to a single item within your loop rather than everything.
0

Featured Post

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick Powershell script I wrote to find old program installations and check versions of a specific file across the network.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
Simple Linear Regression
Introduction to Processes

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question