none
copy/move/append to file name

    Question

  • I have a process in place where another department recieves faxes and then copies those faxes into a fileshare that my dept. manages.  On our side of things we consider this share as the "Source"  we then have a need of copying these files to another share that is monitored by an application that imports the files into a Document Management System which I refer to as the "Destination".

    Currently there is a VBS script that MOVES these files while renaming them.  The rename appends text to the beginning of the file name, but leaves the rest of the name alone.   For instance if the file name is abc123.pdf ... after the move/rename the file name might be "Marketing-abc123.pdf"

    The changed file name shows up in the DMS so that users of the various departments can find their stuff quickly and do what they need to with the files.

    The issue I have is that the VBS script ... which I don't really understand, moves these files to one single location.

    I want to do this with Powershell, but I can't seem to figure out how to append specified text to the file name, yet leave the rest of the file name alone.

    The reason I wish to convert this process to powershell is not only do I have a better understanding of it than VBS, but I want to direct the orginal file to 2 locations (for backup purposes) and to generate a log file for a record of what occurred & when.

    So I need to append text to a file name.  Copy the file to a new location, then MOVE the file to a backup location.  I don't want the code to proceed to delete if it fails to copy which is why I state Move.

    There are several processes like this in place.  One of which doesn't require the appending of text to the file name and the code I am using for that is as follows, I was hoping to modify it to do what I want:


    $Source = "\\SourceServer\Share"
    $Destination = "\\DestinationServer\Share"
    $Bkp = "\\BackupServer\Share"
    if(Test-Path -Path $Source\* -include *.pdf)
    			{
    				Add-Content -Path $Source\copy.log -value "**********BEGIN ACTION @ $time**********"
    				Copy-Item -path $Source\* -include *.pdf -destination $Bkp -passthru | format-table -property LastWriteTime,Name -autosize | out-file $Source\copy.log -Append -Encoding ascii
    				Move-Item -path $Source\*.pdf -destination $Destination
    				Add-Content -Path $Source\copy.log -value "**********STOP ACTION @ $time**********`r`n================================================`r`n"
    				Copy-Item $Source\copy.log $Bkp\copy.log
    			}
    				ELSE
    			{
    				Add-Content -Path $Source\copy.log -value "**********BEGIN ACTION @ $time*********`r`n`r`n0 Files Copied`r`n`r`n**********STOP ACTION @ $time**********`r`n================================================`r`n"
    			}


    • Edited by Wasisname Friday, July 26, 2013 8:41 PM code edit
    Friday, July 26, 2013 8:33 PM

Answers

  • I was able to modify my orginal code by adding in the following line to the script block above the add-content command, to achieve the desired results
    Get-ChildItem $source\* -include *.jpg,*.tif,*.pdf -exclude *.log | % {Rename-item $_.Fullname ( "TextToAppend--" + $_.Name)}



    # When I wrote this only God and I knew what I was doing. Now, only God knows.

    Don't Retire Technet







    • Marked as answer by Wasisname Wednesday, September 04, 2013 8:00 PM
    • Edited by Wasisname Wednesday, September 04, 2013 8:03 PM clarification
    Wednesday, September 04, 2013 8:00 PM

All replies

  • This might work.

    Maybe make the log part a bit nicer.

    $Source = "c:\source"
    $Destination = "C:\destination\"
    Set-location $Source
    $SourceArray = @()
    $SourceArray = Get-Childitem $Source\* -include *.pdf
    Add-Content -Path $Source\copy.log -value "**********BEGIN ACTION @ $time**********"
    
    Foreach($i in $SourceArray){
    
    $oldname = $i.Name
    $NewName = ("Prefix-" + $oldname)
    Rename-Item -Path $oldname -NewName $Newname
    Move-Item -Path ($source + $NewName) -Destination $Destination 
    }
    
    Add-Content -Path $Source\copy.log -value "**********STOP ACTION @ $time**********`r`n================================================`r`n"
    
    Copy-Item $Source\copy.log $Bkp\copy.log




    • Edited by Thom Kortekaas Saturday, July 27, 2013 4:46 PM edit code block
    Saturday, July 27, 2013 4:43 PM
  • Yet another proposal:

    $dep = "department"
    $Destination = "C:\Users\wiz\AppData\Local\Temp\Temp\Dir2"
    gci -Filter "*.txt" | % {
        $name = $_.Name
        Move-Item $_ -Destination ($Destination + "\" + $dep + "_" + $name)
    }

    Kind regard,

    wizend

    Saturday, July 27, 2013 6:05 PM
  • You'll want to use the DirectoryName, BaseName, and Extension properties of the file object, and an iterator to parse the files.  Kind of like this:

    $Source = "\\SourceServer\Share"
    $Destination = "\\DestinationServer\Share"
    $Bkp = "\\BackupServer\Share"
    
    If (Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.ps1") { 
        Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.ps1" |
        ForEach-Object `
        -Begin {
            Add-Content -Path "$Source\copy.log" -Value "**********BEGIN ACTION @ $time**********";
        } `
        -Process {
            $_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ($_.BaseName + ".copied." + $_.Extension));
            $_ |
            Format-Table -Property LastWriteTime,Name -AutoSize | 
            Out-File (Join-Path -Path $Source -ChildPath "copy.log") -Append -Encoding ascii;
        } `
        -End {
            Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********STOP ACTION @ $time**********`r`n================================================`r`n";
    	    Copy-Item -Path (Join-Path -Path $Source -ChildPath "copy.log") -Destination (Join-Path -Path $Bkp -ChildPath "copy.log"); 
        }; 
    } Else {
        Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********BEGIN ACTION @ $time*********`r`n`r`n0 Files Copied`r`n`r`n**********STOP ACTION @ $time**********`r`n================================================`r`n"
    }

    Note that I prefer to use Join-Path for resiliency (because someone alwasy comes through and specifies a path with a trailing backslash if I leave one off, or one without if I include it). 

    If you did some poking, you could use a manual iterator to remove the if/then/else.

    Also note that the -Resolve parameter of Join-Path returns an array of strings containing the FullName attributes of the paths and when piped to Get-Item can be used to populate an iterator and could be used with try/catch to eliminate the if/then/else here in a more elegant fashion.  But I'm out of time for now.


    • Edited by Jordan Mills Saturday, July 27, 2013 8:09 PM asdf
    Saturday, July 27, 2013 8:07 PM
  • okay couldn't resist, this is how you use an iterator to remove the if/then/else and still keep the zero files copied output

    $Source = "\\SourceServer\Share"
    $Destination = "\\DestinationServer\Share"
    $Bkp = "\\BackupServer\Share"
    
    Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.ps1" |
    ForEach-Object `
    -Begin {
        $i = 0
        Add-Content -Path "$Source\copy.log" -Value "**********BEGIN ACTION @ $time**********";
    } `
    -Process {
        $i++
        $_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ($_.BaseName + ".copied." + $_.Extension));
        $_ |
        Format-Table -Property LastWriteTime,Name -AutoSize | 
        Out-File (Join-Path -Path $Source -ChildPath "copy.log") -Append -Encoding ascii;
    } `
    -End {
        Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "$i Files Copied";
        Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********STOP ACTION @ $time**********`r`n";
        Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "================================================`r`n";
        Copy-Item -Path (Join-Path -Path $Source -ChildPath "copy.log") -Destination (Join-Path -Path $Bkp -ChildPath "copy.log"); 
    }; 

    Saturday, July 27, 2013 8:13 PM
  • Hi,

    Just checking in to see if the suggestions were helpful. Please let us know if you would like further assistance.

    If you have any feedback on our support, please click here .


    Cataleya Li
    TechNet Community Support

    Monday, July 29, 2013 6:20 AM
    Moderator
  • I'll need a day or so to vet out these suggestions, been out for the weekend and all and of course have to hit the ground running on a Monday.

    Thanks to everyone so far!

    • Edited by Wasisname Monday, July 29, 2013 1:49 PM additional comment
    Monday, July 29, 2013 1:49 PM
  • I'm not noticing a Move-Item action in this.  Am I missing something or should I add it into the -End portion after the Copy-Item?

    Also I don't want the name of the file to end up like ABC123.copied.pdf, but rather copied.abc123.pdf, because this is what the department(s) are used to.  can I change the code to:

    ("Copied--" + $_.BaseName + $_.extension)

    Monday, July 29, 2013 6:26 PM
  • I prefer to keep the If/then/else because this portion of the code is nested in another If/Then/Else for alert/warning purposes.
    Monday, July 29, 2013 6:28 PM
  • Jordan, When I attempt to use the code you provided I am getting errors indicating that PS doesn't understand the -begin, -process, & -end
    Tuesday, July 30, 2013 8:31 PM
  • Jordan, When I attempt to use the code you provided I am getting errors indicating that PS doesn't understand the -begin, -process, & -end

    Make sure you don't remove the backtick at the end of the preceeding line.  Or just run them together: foreach-object -begin { <# beginblock #> } -process { <#process block #> }

    Note that those are backtick characters at the ends of the lines immediately before -begin etc, not single quotes.

    You're using at least powershell v2 right?

    Tuesday, July 30, 2013 8:44 PM
  • I am using PS v 3.0 on Windows 7 64 bit OS running the PS console as Administrator.

    Here is the code I'm trying to run Minus the setting of the objects like $source etc ... Just to be clear they are included in the script, I just didn't include them here:

    If (Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.pdf","*.jpg","*.tif"))
    			{ 
    				Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.pdf","*.jpg","*.tif" |
    				ForEach-Object`
    				-Begin{
    						Add-Content -Path "$Source\copy.log" -Value "**********BEGIN ACTION @ $time**********";
    					}`
    				-Process{
    						$_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" + $_.BaseName + $_.Extension));
    						$_ |
    						Format-Table -Property LastWriteTime,Name -AutoSize |
    						Out-File (Join-Path -Path $Source -ChildPath "copy.log") -Append -Encoding ascii;						
    					}`
    				-End{
    						Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********STOP ACTION @ $time**********`r`n================================================`r`n";
    						Copy-Item -Path (Join-Path -Path $Source -ChildPath "copy.log") -Destination (Join-Path -Path $Bkp -ChildPath "copy.log"); 
    					}; 
    			}
    			Else
    			{
    				Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********BEGIN ACTION @ $time*********`r`n`r`n0 Files Copied`r`n`r`n**********STOP ACTION @ $time**********`r`n================================================`r`n"
    			}

    Here are the errors:

    At C:\Scripts\PowerShell\1-MoveFax.ps1:22 char:100
    + ... "*.jpg","*.tif"))
    +                    ~
    Missing statement block after If ( condition ).
    At C:\Scripts\PowerShell\1-MoveFax.ps1:22 char:101
    + ... *.jpg","*.tif"))
    +                    ~
    Unexpected token ')' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:30 char:17
    +                         $_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" + $_.B ...
    +                                   ~
    Missing ')' in method call.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:30 char:17
    +                         $_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" + $_.B ...
    +                                   ~~~~~~~~~
    Unexpected token 'Join-Path' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:29 char:13
    +                 -Process{
    +                         ~
    Missing closing '}' in statement block.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:23 char:4
    +             {
    +             ~
    Missing closing '}' in statement block.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:30 char:104
    + ... + $_.Extension));
    +                    ~
    Unexpected token ')' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:34 char:6
    +                     }`
    +                     ~
    Unexpected token '}' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:39 char:4
    +             }
    +             ~
    Unexpected token '}' in expression or statement.
        + CategoryInfo          : ParserError: (:) [], ParseException
        + FullyQualifiedErrorId : MissingStatementBlock

    Wednesday, July 31, 2013 2:49 PM
  • Remove the last ) in 22.  It should be:

    If (Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.pdf","*.jpg","*.tif")

    Also remove the trailing semicolon from the last line before every close brace ("}").  It seems to not like those.  Ex, this:

    				-Begin{
    						Add-Content -Path "$Source\copy.log" -Value "**********BEGIN ACTION @ $time**********";
    					}`

    should be:

    				-Begin{
    						Add-Content -Path "$Source\copy.log" -Value "**********BEGIN ACTION @ $time**********"
    					}`

    I think that one was my fault.
    Wednesday, July 31, 2013 2:53 PM
  • code:

    If (Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.pdf","*.jpg","*.tif")
    			{ 
    				Get-ChildItem -Path (Join-Path -Path $Source -ChildPath "*") -Include "*.pdf","*.jpg","*.tif" |
    				ForEach-Object`
    				-Begin	{
    						Add-Content -Path "$Source\copy.log" -Value "**********BEGIN ACTION @ $time**********"
    						}`
    				-Process{
    						$_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" + $_.BaseName + $_.Extension));
    						$_ |
    						Format-Table -Property LastWriteTime,Name -AutoSize |
    						Out-File (Join-Path -Path $Source -ChildPath "copy.log") -Append -Encoding ascii						
    					}`
    				-End{
    						Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********STOP ACTION @ $time**********`r`n================================================`r`n";
    						Copy-Item -Path (Join-Path -Path $Source -ChildPath "copy.log") -Destination (Join-Path -Path $Bkp -ChildPath "copy.log") 
    					}; 
    			}
    			Else
    			{
    				Add-Content -Path (Join-Path -Path $Source -ChildPath "copy.log") -Value "**********BEGIN ACTION @ $time*********`r`n`r`n0 Files Copied`r`n`r`n**********STOP ACTION @ $time**********`r`n================================================`r`n"
    			}

    Errors:

    At C:\Scripts\PowerShell\1-MoveFax.ps1:27 char:24
    +                 -Process{$_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" ...
    +                                    ~
    Missing ')' in method call.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:27 char:24
    +                 -Process{$_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" ...
    +                                    ~~~~~~~~~
    Unexpected token 'Join-Path' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:27 char:13
    +                 -Process{$_.CopyTo(Join-Path -Path $_.DirectoryName -ChildPath ("ThisTest--" ...
    +                         ~
    Missing closing '}' in statement block.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:23 char:4
    +             {
    +             ~
    Missing closing '}' in statement block.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:27 char:111
    + ... + $_.Extension));
    +                    ~
    Unexpected token ')' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:30 char:87
    + ... -Encoding ascii}`
    +                    ~
    Unexpected token '}' in expression or statement.
    At C:\Scripts\PowerShell\1-MoveFax.ps1:35 char:4
    +             }
    +             ~
    Unexpected token '}' in expression or statement.
        + CategoryInfo          : ParserError: (:) [], ParseException
        + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

    Wednesday, July 31, 2013 3:23 PM
  • I was able to modify my orginal code by adding in the following line to the script block above the add-content command, to achieve the desired results
    Get-ChildItem $source\* -include *.jpg,*.tif,*.pdf -exclude *.log | % {Rename-item $_.Fullname ( "TextToAppend--" + $_.Name)}



    # When I wrote this only God and I knew what I was doing. Now, only God knows.

    Don't Retire Technet







    • Marked as answer by Wasisname Wednesday, September 04, 2013 8:00 PM
    • Edited by Wasisname Wednesday, September 04, 2013 8:03 PM clarification
    Wednesday, September 04, 2013 8:00 PM