• Status: Solved
  • Priority: Medium
  • Security: Private
  • Views: 95
  • Last Modified:

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
0
0rwell
Asked:
0rwell
  • 3
  • 2
2 Solutions
 
Chris DentPowerShell DeveloperCommented:
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
 
Chris DentPowerShell DeveloperCommented:
By the way, this includes hard termination if you have an unhandled exception anywhere, including within the remotely executed script block.
0
 
oBdACommented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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

A Cyber Security RX to Protect Your Organization

Join us on December 13th for a webinar to learn how medical providers can defend against malware with a cyber security "Rx" that supports a healthy technology adoption plan for every healthcare organization.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now