Copying files using PowerShell

I'm a newbie to PowerShell and have implemented the following script to copy files to two servers and then delete the files from the original location:

# unregistering the event
Unregister-Event PDFCreated -ErrorAction SilentlyContinue

[String] $folder = 'd:\temp\contract'           # root path of the directory to be monitored
[String] $errorLog = $folder + '\error.txt'     # error log file name
[String] $errorLogMsg = ''                      # error log message
[String] $filter = '*.pdf'                      # wildcard filter
[Boolean] $includeSubdir = $true                # indicates if subdirectories should be monitored

# creation of the file system watcher
try
{
    $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $includeSubdir;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
}
catch [Exception] 
{    
    # logging the error
    $errorLogMsg = 'Error on creating object FileSystemWatcher'
    AddLogMessage $errorLog $errorLogMsg $_.Exception.GetType().FullName $_.Exception.Message
    Exit
}

# registering the creation of file
Register-ObjectEvent $fsw Created -SourceIdentifier PDFCreated -Action { 
    [String] $name = $Event.SourceEventArgs.Name     # PDF file name
    [String] $timestamp = $Event.TimeGenerated       # date/time PDF file was created
    [String] $message = ""                           # event message to be logged

    # creating the directory of the event log file (if already exists, no error will be returned)
    [DateTime] $dt = $Event.TimeGenerated                              # date/time PDF file was created
    [String] $year = $dt.ToString("yyyy")                              # year PDF file was created
    [String] $month = $dt.ToString("MM")                               # month PDF file was created
    [String] $logFolder = $folder + "\log\" + $year + "\" + $month     # folder of the event log file
    try
    {
        New-Item -ItemType Directory -Path $logFolder
    }
    catch [Exception]
    {
        # logging the error
        $errorLogMsg = 'Error on creating directory ' + $logFolder
        AddLogMessage $errorLog $errorLogMsg $_.Exception.GetType().FullName $_.Exception.Message
        Exit
    }

    # setting the full event log file name
    [String] $day = $dt.ToString("dd")                                                     # day PDF file was created
    [String] $eventLog = $logFolder + "\" + $year + "-" + $month + "-" + $day + ".txt"     # event log file name
    [String] $fullFileName = $folder + "\" + $name     # full PDF file name
    [String] $clubId = $name.Substring(0, 3);          # club

    # logging the event (creation of PDF file)
    $message = "File $fullFileName created"
    AddLogMessage $eventLog $message '' ''

    # copying file to server #1
    try
    {
        # connecting to server #1
        Net Use Z: /delete
        Net Use Z: \\xxx.xxx.xxx.xxx\shared_drive /user:'domain1\user1' 'password1'

        # although the statement is wrapped in a try/catch block, an error in Net Use will not raise an exception; so, $LastExitCode must be checked
        if ($LastExitCode -ne 0)
        {
            # logging the error
            $errorLogMsg = 'Error ' + $LastExitCode.ToString() + ' on connecting to ' + '\\xxx.xxx.xxx.xxx\shared_drive\ via Net Use statement'
            AddLogMessage $eventLog $errorLogMsg
            Exit
        }

        # copying the file to the directory identified by $clubId
        Copy-Item $fullFileName Z:$clubId
    }
    catch [Exception]
    {
        # logging the error
        $errorLogMsg = 'Error on copying file ' + $fullFileName + ' to ' + '\\xxx.xxx.xxx.xxx\shared_drive\' + $clubId
        AddLogMessage $eventLog $errorLogMsg $_.Exception.GetType().FullName $_.Exception.Message
        Exit
    }
    finally
    {
        Net Use Z: /delete     # disconnecting from server1
    }

    # logging the event (copy of PDF file to server1)
    $message = "File $fullFileName copied to server1\shared_drive\" + $clubId
    AddLogMessage $eventLog $message '' ''

    [String] $directoryMA = ''
    .
    .
    . 
    statements to set the value of $directoryMA

    # copying file to server2
    try
    {
        # connecting to server2
        Net Use Z: /delete
        Net Use Z: \\server2\shared_drive /user:'domain2\user2' 'password2'

        # although the statement is wrapped in a try/catch block, an error in Net Use will not raise an exception; so, $LastExitCode must be checked
        if ($LastExitCode -ne 0)
        {
            # logging the error
            $errorLogMsg = 'Error ' + $LastExitCode.ToString() + ' on connecting to ' + '\\server2\shared_drive\ via Net Use statement'
            AddLogMessage $eventLog $errorLogMsg
            Exit
        }

        # copying the file
        Copy-Item $fullFileName Z:$directoryMA
    }
    catch [Exception]
    {
        # logging the error
        $errorLogMsg = 'Error on copying file ' + $fullFileName + ' to ' + $directoryMA
        AddLogMessage $eventLog $errorLogMsg $_.Exception.GetType().FullName $_.Exception.Message
        Exit
    }
    finally
    {
        Net Use Z: /delete     # disconnecting from server2
    }

    # logging the event (copy of PDF file to server2)
    $message = "File $fullFileName copied to " + $directoryMA
    AddLogMessage $eventLog $message '' ''

    # deleting the file
    try
    {
        Remove-Item $fullFileName
    }
    catch [Exception]
    {
        # logging the error
        $errorLogMsg = 'Error on deleting file ' + $fullFileName
        AddLogMessage $eventLog $errorLogMsg $_.Exception.GetType().FullName $_.Exception.Message
        Exit
    }

    # logging the event (delete of PDF file)
    $message = "File $fullFileName deleted"
    AddLogMessage $eventLog $message '' ''
}

Open in new window


server1 and server2 are located outside of our internal network.

Accounts used to access server1 and server2 have the proper rights to save files in the respective servers; using the PowerShell command prompt, I was able to copy files to the servers to validate the credentials.

In order to test the script, file test.pdf was copied to one of the directories being monitored.
In the event log file, the following entries were logged:
09/18/2014 12:12:36 File d:\temp\contract\254\test.pdf created
09/18/2014 12:12:37 File d:\temp\contract\254\test.pdf copied to server1\shared_drive\254
09/18/2014 12:12:37 File d:\temp\contract\254\test.pdf copied to server2\shared_drive
09/18/2014 12:12:37 File d:\temp\contract\254\test.pdf deleted

The problem is that the copies to server1 and server2 were not executed.
Despite the try/catch blocks, no exceptions were raised either.

Any suggestions or comments are much appreciated.
Thank you in advance.
bbwbAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

footechCommented:
Try changing the erroraction, either for the whole script or just particular commands.  Like line 36 could be
New-Item -ItemType Directory -Path $logFolder -errorAction Stop

Open in new window

and line 73
Copy-Item $fullFileName Z:$clubId  -errorAction Stop

Open in new window

Try/Catch will only capture terminating errors.  Unfortunately it's not always clear what is a terminating vs. a non-terminating error.  You can also set $ErrorActionPreference to "Stop" to make the setting for the script as a whole, and still use the -errorAction parameter for individual commands if you wish to change it.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.