Powershell Script to Create folder, if file exists












0














Hi all I require assistance with my Powershell script(I'm new to Powershell). What I'm trying to accomplish is currently I have a script setup to Convert RTF documents to PDF's and save it to a directory. What I want my script to do now is, when my script searches Recursively through my source directory, if a RTF is found, I wish to create the matching directory that it was found in, in my destination directory and save the file in the destinations new directory.



So as follows:
If a RTF is found in the following directory C:userstestuserfolder1newuser , my current script will convert the documents and save it in C:usersfolder2. So if a file was found in the newuser directory, I want to create a newuser directory in C:usersfolder2newuser and save the converted document in the directory, Please assist, I'm new to powershell.



$source = "C:userstestuserfolder1"
$destination = "C:userstestuserfolder2"


$word_app = New-Object -ComObject word.application



#Convert RTF to PDF

Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

$document = $word_app.Documents.Open($_.FullName)

$pdf_filename = "$destination$($_.BaseName).pdf"

$document.SaveAs([ref] $pdf_filename, [ref] 17)

$document.Close()

}

$word_app.Quit()









share|improve this question



























    0














    Hi all I require assistance with my Powershell script(I'm new to Powershell). What I'm trying to accomplish is currently I have a script setup to Convert RTF documents to PDF's and save it to a directory. What I want my script to do now is, when my script searches Recursively through my source directory, if a RTF is found, I wish to create the matching directory that it was found in, in my destination directory and save the file in the destinations new directory.



    So as follows:
    If a RTF is found in the following directory C:userstestuserfolder1newuser , my current script will convert the documents and save it in C:usersfolder2. So if a file was found in the newuser directory, I want to create a newuser directory in C:usersfolder2newuser and save the converted document in the directory, Please assist, I'm new to powershell.



    $source = "C:userstestuserfolder1"
    $destination = "C:userstestuserfolder2"


    $word_app = New-Object -ComObject word.application



    #Convert RTF to PDF

    Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

    $document = $word_app.Documents.Open($_.FullName)

    $pdf_filename = "$destination$($_.BaseName).pdf"

    $document.SaveAs([ref] $pdf_filename, [ref] 17)

    $document.Close()

    }

    $word_app.Quit()









    share|improve this question

























      0












      0








      0







      Hi all I require assistance with my Powershell script(I'm new to Powershell). What I'm trying to accomplish is currently I have a script setup to Convert RTF documents to PDF's and save it to a directory. What I want my script to do now is, when my script searches Recursively through my source directory, if a RTF is found, I wish to create the matching directory that it was found in, in my destination directory and save the file in the destinations new directory.



      So as follows:
      If a RTF is found in the following directory C:userstestuserfolder1newuser , my current script will convert the documents and save it in C:usersfolder2. So if a file was found in the newuser directory, I want to create a newuser directory in C:usersfolder2newuser and save the converted document in the directory, Please assist, I'm new to powershell.



      $source = "C:userstestuserfolder1"
      $destination = "C:userstestuserfolder2"


      $word_app = New-Object -ComObject word.application



      #Convert RTF to PDF

      Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

      $document = $word_app.Documents.Open($_.FullName)

      $pdf_filename = "$destination$($_.BaseName).pdf"

      $document.SaveAs([ref] $pdf_filename, [ref] 17)

      $document.Close()

      }

      $word_app.Quit()









      share|improve this question













      Hi all I require assistance with my Powershell script(I'm new to Powershell). What I'm trying to accomplish is currently I have a script setup to Convert RTF documents to PDF's and save it to a directory. What I want my script to do now is, when my script searches Recursively through my source directory, if a RTF is found, I wish to create the matching directory that it was found in, in my destination directory and save the file in the destinations new directory.



      So as follows:
      If a RTF is found in the following directory C:userstestuserfolder1newuser , my current script will convert the documents and save it in C:usersfolder2. So if a file was found in the newuser directory, I want to create a newuser directory in C:usersfolder2newuser and save the converted document in the directory, Please assist, I'm new to powershell.



      $source = "C:userstestuserfolder1"
      $destination = "C:userstestuserfolder2"


      $word_app = New-Object -ComObject word.application



      #Convert RTF to PDF

      Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

      $document = $word_app.Documents.Open($_.FullName)

      $pdf_filename = "$destination$($_.BaseName).pdf"

      $document.SaveAs([ref] $pdf_filename, [ref] 17)

      $document.Close()

      }

      $word_app.Quit()






      powershell






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 19 '18 at 16:46









      Josh Adams

      82




      82






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Then you will need to use a combination of Split-Path and String.Replace to build a new path from your source file's path and create the new folder and file. A caveat of using String.Replace is that it is case sensitive so your paths need to be converted to a common case, like lower case. An example of using Split-Path and String.Replace is below:



          $Source = "C:UserstestuserFolder1"
          $Destination = "C:UserstestuserFolder2"

          $ExampleFile = $Source + "newuserthisfile.rtf"

          #Use a combination of Split-Path and String.Replace
          #Split-Path will take the full path to your file, and return just the parent folder path.
          #String.Replace will then remove the $Source path from the remaining path.
          #Finally we concatenate the new path with the $Destination path to get our new folder path.

          $NewFolder = Split-Path $ExampleFile
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder1newuser

          $NewFolder = $NewFolder.ToLower().Replace($Source.ToLower(), "")
          Write-Host $NewFolder
          # Output: newuser

          $NewFolder = $Destination + $NewFolder
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Or, more simply:
          $NewFolder = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), ""))
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Create the folder with ErrorAction = SilentlyContinue so that it doesn't throw an error if the folder already exists:
          New-Item -Path $NewFolder -Type directory -ErrorAction SilentlyContinue

          #Or, combine everything together and you have:
          New-Item -Path $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) -Type directory -ErrorAction SilentlyContinue


          Your new code would look like this:



          $source = "C:userstestuserfolder1"
          $destination = "C:userstestuserfolder2"

          $word_app = New-Object -ComObject word.application

          #Convert RTF to PDF

          Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

          $document = $word_app.Documents.Open($_.FullName)

          #Create new path and filename from source path and filename
          $pdf_filename = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) + "" + $_.BaseName + ".pdf"

          #Create new folder tree
          New-Item -path $(Split-Path $pdf_filename) -Type directory -ErrorAction SilentlyContinue

          $document.SaveAs([ref] $pdf_filename, [ref] 17)

          $document.Close()

          }

          $word_app.Quit()





          share|improve this answer























          • Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
            – Josh Adams
            Dec 20 '18 at 12:35










          • Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
            – Josh Adams
            Dec 20 '18 at 12:42











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "3"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1385974%2fpowershell-script-to-create-folder-if-file-exists%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Then you will need to use a combination of Split-Path and String.Replace to build a new path from your source file's path and create the new folder and file. A caveat of using String.Replace is that it is case sensitive so your paths need to be converted to a common case, like lower case. An example of using Split-Path and String.Replace is below:



          $Source = "C:UserstestuserFolder1"
          $Destination = "C:UserstestuserFolder2"

          $ExampleFile = $Source + "newuserthisfile.rtf"

          #Use a combination of Split-Path and String.Replace
          #Split-Path will take the full path to your file, and return just the parent folder path.
          #String.Replace will then remove the $Source path from the remaining path.
          #Finally we concatenate the new path with the $Destination path to get our new folder path.

          $NewFolder = Split-Path $ExampleFile
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder1newuser

          $NewFolder = $NewFolder.ToLower().Replace($Source.ToLower(), "")
          Write-Host $NewFolder
          # Output: newuser

          $NewFolder = $Destination + $NewFolder
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Or, more simply:
          $NewFolder = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), ""))
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Create the folder with ErrorAction = SilentlyContinue so that it doesn't throw an error if the folder already exists:
          New-Item -Path $NewFolder -Type directory -ErrorAction SilentlyContinue

          #Or, combine everything together and you have:
          New-Item -Path $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) -Type directory -ErrorAction SilentlyContinue


          Your new code would look like this:



          $source = "C:userstestuserfolder1"
          $destination = "C:userstestuserfolder2"

          $word_app = New-Object -ComObject word.application

          #Convert RTF to PDF

          Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

          $document = $word_app.Documents.Open($_.FullName)

          #Create new path and filename from source path and filename
          $pdf_filename = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) + "" + $_.BaseName + ".pdf"

          #Create new folder tree
          New-Item -path $(Split-Path $pdf_filename) -Type directory -ErrorAction SilentlyContinue

          $document.SaveAs([ref] $pdf_filename, [ref] 17)

          $document.Close()

          }

          $word_app.Quit()





          share|improve this answer























          • Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
            – Josh Adams
            Dec 20 '18 at 12:35










          • Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
            – Josh Adams
            Dec 20 '18 at 12:42
















          0














          Then you will need to use a combination of Split-Path and String.Replace to build a new path from your source file's path and create the new folder and file. A caveat of using String.Replace is that it is case sensitive so your paths need to be converted to a common case, like lower case. An example of using Split-Path and String.Replace is below:



          $Source = "C:UserstestuserFolder1"
          $Destination = "C:UserstestuserFolder2"

          $ExampleFile = $Source + "newuserthisfile.rtf"

          #Use a combination of Split-Path and String.Replace
          #Split-Path will take the full path to your file, and return just the parent folder path.
          #String.Replace will then remove the $Source path from the remaining path.
          #Finally we concatenate the new path with the $Destination path to get our new folder path.

          $NewFolder = Split-Path $ExampleFile
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder1newuser

          $NewFolder = $NewFolder.ToLower().Replace($Source.ToLower(), "")
          Write-Host $NewFolder
          # Output: newuser

          $NewFolder = $Destination + $NewFolder
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Or, more simply:
          $NewFolder = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), ""))
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Create the folder with ErrorAction = SilentlyContinue so that it doesn't throw an error if the folder already exists:
          New-Item -Path $NewFolder -Type directory -ErrorAction SilentlyContinue

          #Or, combine everything together and you have:
          New-Item -Path $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) -Type directory -ErrorAction SilentlyContinue


          Your new code would look like this:



          $source = "C:userstestuserfolder1"
          $destination = "C:userstestuserfolder2"

          $word_app = New-Object -ComObject word.application

          #Convert RTF to PDF

          Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

          $document = $word_app.Documents.Open($_.FullName)

          #Create new path and filename from source path and filename
          $pdf_filename = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) + "" + $_.BaseName + ".pdf"

          #Create new folder tree
          New-Item -path $(Split-Path $pdf_filename) -Type directory -ErrorAction SilentlyContinue

          $document.SaveAs([ref] $pdf_filename, [ref] 17)

          $document.Close()

          }

          $word_app.Quit()





          share|improve this answer























          • Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
            – Josh Adams
            Dec 20 '18 at 12:35










          • Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
            – Josh Adams
            Dec 20 '18 at 12:42














          0












          0








          0






          Then you will need to use a combination of Split-Path and String.Replace to build a new path from your source file's path and create the new folder and file. A caveat of using String.Replace is that it is case sensitive so your paths need to be converted to a common case, like lower case. An example of using Split-Path and String.Replace is below:



          $Source = "C:UserstestuserFolder1"
          $Destination = "C:UserstestuserFolder2"

          $ExampleFile = $Source + "newuserthisfile.rtf"

          #Use a combination of Split-Path and String.Replace
          #Split-Path will take the full path to your file, and return just the parent folder path.
          #String.Replace will then remove the $Source path from the remaining path.
          #Finally we concatenate the new path with the $Destination path to get our new folder path.

          $NewFolder = Split-Path $ExampleFile
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder1newuser

          $NewFolder = $NewFolder.ToLower().Replace($Source.ToLower(), "")
          Write-Host $NewFolder
          # Output: newuser

          $NewFolder = $Destination + $NewFolder
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Or, more simply:
          $NewFolder = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), ""))
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Create the folder with ErrorAction = SilentlyContinue so that it doesn't throw an error if the folder already exists:
          New-Item -Path $NewFolder -Type directory -ErrorAction SilentlyContinue

          #Or, combine everything together and you have:
          New-Item -Path $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) -Type directory -ErrorAction SilentlyContinue


          Your new code would look like this:



          $source = "C:userstestuserfolder1"
          $destination = "C:userstestuserfolder2"

          $word_app = New-Object -ComObject word.application

          #Convert RTF to PDF

          Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

          $document = $word_app.Documents.Open($_.FullName)

          #Create new path and filename from source path and filename
          $pdf_filename = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) + "" + $_.BaseName + ".pdf"

          #Create new folder tree
          New-Item -path $(Split-Path $pdf_filename) -Type directory -ErrorAction SilentlyContinue

          $document.SaveAs([ref] $pdf_filename, [ref] 17)

          $document.Close()

          }

          $word_app.Quit()





          share|improve this answer














          Then you will need to use a combination of Split-Path and String.Replace to build a new path from your source file's path and create the new folder and file. A caveat of using String.Replace is that it is case sensitive so your paths need to be converted to a common case, like lower case. An example of using Split-Path and String.Replace is below:



          $Source = "C:UserstestuserFolder1"
          $Destination = "C:UserstestuserFolder2"

          $ExampleFile = $Source + "newuserthisfile.rtf"

          #Use a combination of Split-Path and String.Replace
          #Split-Path will take the full path to your file, and return just the parent folder path.
          #String.Replace will then remove the $Source path from the remaining path.
          #Finally we concatenate the new path with the $Destination path to get our new folder path.

          $NewFolder = Split-Path $ExampleFile
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder1newuser

          $NewFolder = $NewFolder.ToLower().Replace($Source.ToLower(), "")
          Write-Host $NewFolder
          # Output: newuser

          $NewFolder = $Destination + $NewFolder
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Or, more simply:
          $NewFolder = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), ""))
          Write-Host $NewFolder
          # Output: C:UserstestuserFolder2newuser

          #Create the folder with ErrorAction = SilentlyContinue so that it doesn't throw an error if the folder already exists:
          New-Item -Path $NewFolder -Type directory -ErrorAction SilentlyContinue

          #Or, combine everything together and you have:
          New-Item -Path $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) -Type directory -ErrorAction SilentlyContinue


          Your new code would look like this:



          $source = "C:userstestuserfolder1"
          $destination = "C:userstestuserfolder2"

          $word_app = New-Object -ComObject word.application

          #Convert RTF to PDF

          Get-ChildItem -Path $source -Filter *.rtf? -Recurse | ForEach-Object {

          $document = $word_app.Documents.Open($_.FullName)

          #Create new path and filename from source path and filename
          $pdf_filename = $($Destination + $(Split-Path $ExampleFile).ToLower().Replace($Source.ToLower(), "")) + "" + $_.BaseName + ".pdf"

          #Create new folder tree
          New-Item -path $(Split-Path $pdf_filename) -Type directory -ErrorAction SilentlyContinue

          $document.SaveAs([ref] $pdf_filename, [ref] 17)

          $document.Close()

          }

          $word_app.Quit()






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 19 '18 at 18:53

























          answered Dec 19 '18 at 18:44









          Appleoddity

          7,12621124




          7,12621124












          • Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
            – Josh Adams
            Dec 20 '18 at 12:35










          • Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
            – Josh Adams
            Dec 20 '18 at 12:42


















          • Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
            – Josh Adams
            Dec 20 '18 at 12:35










          • Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
            – Josh Adams
            Dec 20 '18 at 12:42
















          Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
          – Josh Adams
          Dec 20 '18 at 12:35




          Thank You, for you help, I just have 1 question, in your 2nd post you have $ExampleFile stated, but I don't see it reference anywhere is that suppose to be used in their after split-path. I'm a little confused.
          – Josh Adams
          Dec 20 '18 at 12:35












          Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
          – Josh Adams
          Dec 20 '18 at 12:42




          Ignore my last comment, my brain hasn't caught up with me yet, sorry about that.
          – Josh Adams
          Dec 20 '18 at 12:42


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Super User!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f1385974%2fpowershell-script-to-create-folder-if-file-exists%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          flock() on closed filehandle LOCK_FILE at /usr/bin/apt-mirror

          Mangá

           ⁒  ․,‪⁊‑⁙ ⁖, ⁇‒※‌, †,⁖‗‌⁝    ‾‸⁘,‖⁔⁣,⁂‾
”‑,‥–,‬ ,⁀‹⁋‴⁑ ‒ ,‴⁋”‼ ⁨,‷⁔„ ‰′,‐‚ ‥‡‎“‷⁃⁨⁅⁣,⁔
⁇‘⁔⁡⁏⁌⁡‿‶‏⁨ ⁣⁕⁖⁨⁩⁥‽⁀  ‴‬⁜‟ ⁃‣‧⁕‮ …‍⁨‴ ⁩,⁚⁖‫ ,‵ ⁀,‮⁝‣‣ ⁑  ⁂– ․, ‾‽ ‏⁁“⁗‸ ‾… ‹‡⁌⁎‸‘ ‡⁏⁌‪ ‵⁛ ‎⁨ ―⁦⁤⁄⁕