?
SolvedPrivate

powershell try catch  and $ErrorActionPreference = continue

Posted on 2017-04-18
6
Medium Priority
?
92 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
Q2 2017 - Latest Malware & Internet Attacks

WatchGuard’s Threat Lab is a group of dedicated threat researchers committed to helping you stay ahead of the bad guys by providing in-depth analysis of the top security threats to your network.  Check out our latest Quarterly Internet Security Report!

 

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

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!

Question has a verified solution.

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

Previously, on our Nano Server Deployment series, we've created a new nano server image and deployed it on a physical server in part 2. Now we will go through configuration.
Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Progress

649 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