SolvedPrivate

powershell try catch  and $ErrorActionPreference = continue

Posted on 2017-04-18
6
23 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
  • 3
  • 2
6 Comments
 
LVL 71

Expert Comment

by:Chris Dent
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 250 total points
By the way, this includes hard termination if you have an unhandled exception anywhere, including within the remotely executed script block.
0
 
LVL 84

Accepted Solution

by:
oBdA earned 250 total points
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
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 

Author Closing Comment

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

Author Comment

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

Expert Comment

by:Chris Dent
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

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Join & Write a Comment

Suggested Solutions

This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

756 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