Solved

Copying files using PowerShell

Posted on 2014-09-29
3
182 Views
Last Modified: 2015-02-04
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.
0
Comment
Question by:bbwb
[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 Comments
 
LVL 40

Accepted Solution

by:
footech earned 500 total points
ID: 40350646
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

Featured Post

Free eBook: Backup on AWS

Everything you need to know about backup and disaster recovery with AWS, for FREE!

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…
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…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

705 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