Solved

Copying files using PowerShell

Posted on 2014-09-29
3
137 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
3 Comments
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
Comment Utility
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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
A procedure for exporting installed hotfix details of remote computers using powershell
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

744 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now