Link to home
Start Free TrialLog in
Avatar of Georges Orwell
Georges OrwellFlag for France

asked on

powershell try catch and $ErrorActionPreference = continue

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
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

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?
SOLUTION
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Georges Orwell

ASKER

Thanks, it's more explicit.
@Chris Dent
I just wanted to catch IIS and Filesystem errors
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.