Windows Power Shell rename files












1















I am sort of new to scripting and here's my task:



A folder with X files. Each file contains some Word documents, Excel sheets, etc. In these files, there is a client name and I need to assign an ID number.



This change will affect all the files in this folder that contain this client's name.



How can do this using Windows Power Shell?



$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace " JOHN ", "123" } |
Set-Content $file.PSPath
}


Is this the right approach ?










share|improve this question




















  • 1





    you are going to have to do things differently. [grin] PoSh cannot directly edit word docs or excel spreadsheets. you can install a PoSh module to handle the spreadsheets [i think ImportExcel is the name of one such]. to edit the MSWord docs will require using COM to open MSWord and control it. look up using COM objects with powershell. ///// as an aside, the PSPath parameter is not the one that is usually recommended for what you are doing. instead use the .FullName property.

    – Lee_Dailey
    Nov 19 '18 at 23:30











  • Do you want to rename files, or do you want to modify the content of files? Those are two entirely different operations.

    – Ansgar Wiechers
    Nov 20 '18 at 0:32













  • Word and Excel documents are stored in a proprietary XML type format. You really can't edit the contents of these documents with powershell. Take a look at MS Office Interop. docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…

    – P.Brian.Mackey
    Nov 20 '18 at 4:03











  • @AnsgarWiechers modify the content. Example : change a person name for a number in all of the files that have this persons name

    – user91
    Nov 20 '18 at 12:01











  • If you want to modify the content of files the way to do that depends on the file type as Lee_Dailey already pointed out. Not all files are plaintext files (MS Office files specifically aren't).

    – Ansgar Wiechers
    Nov 20 '18 at 13:49
















1















I am sort of new to scripting and here's my task:



A folder with X files. Each file contains some Word documents, Excel sheets, etc. In these files, there is a client name and I need to assign an ID number.



This change will affect all the files in this folder that contain this client's name.



How can do this using Windows Power Shell?



$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace " JOHN ", "123" } |
Set-Content $file.PSPath
}


Is this the right approach ?










share|improve this question




















  • 1





    you are going to have to do things differently. [grin] PoSh cannot directly edit word docs or excel spreadsheets. you can install a PoSh module to handle the spreadsheets [i think ImportExcel is the name of one such]. to edit the MSWord docs will require using COM to open MSWord and control it. look up using COM objects with powershell. ///// as an aside, the PSPath parameter is not the one that is usually recommended for what you are doing. instead use the .FullName property.

    – Lee_Dailey
    Nov 19 '18 at 23:30











  • Do you want to rename files, or do you want to modify the content of files? Those are two entirely different operations.

    – Ansgar Wiechers
    Nov 20 '18 at 0:32













  • Word and Excel documents are stored in a proprietary XML type format. You really can't edit the contents of these documents with powershell. Take a look at MS Office Interop. docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…

    – P.Brian.Mackey
    Nov 20 '18 at 4:03











  • @AnsgarWiechers modify the content. Example : change a person name for a number in all of the files that have this persons name

    – user91
    Nov 20 '18 at 12:01











  • If you want to modify the content of files the way to do that depends on the file type as Lee_Dailey already pointed out. Not all files are plaintext files (MS Office files specifically aren't).

    – Ansgar Wiechers
    Nov 20 '18 at 13:49














1












1








1








I am sort of new to scripting and here's my task:



A folder with X files. Each file contains some Word documents, Excel sheets, etc. In these files, there is a client name and I need to assign an ID number.



This change will affect all the files in this folder that contain this client's name.



How can do this using Windows Power Shell?



$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace " JOHN ", "123" } |
Set-Content $file.PSPath
}


Is this the right approach ?










share|improve this question
















I am sort of new to scripting and here's my task:



A folder with X files. Each file contains some Word documents, Excel sheets, etc. In these files, there is a client name and I need to assign an ID number.



This change will affect all the files in this folder that contain this client's name.



How can do this using Windows Power Shell?



$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace " JOHN ", "123" } |
Set-Content $file.PSPath
}


Is this the right approach ?







powershell scripting






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 0:08









mklement0

131k20245282




131k20245282










asked Nov 19 '18 at 22:59









user91user91

307




307








  • 1





    you are going to have to do things differently. [grin] PoSh cannot directly edit word docs or excel spreadsheets. you can install a PoSh module to handle the spreadsheets [i think ImportExcel is the name of one such]. to edit the MSWord docs will require using COM to open MSWord and control it. look up using COM objects with powershell. ///// as an aside, the PSPath parameter is not the one that is usually recommended for what you are doing. instead use the .FullName property.

    – Lee_Dailey
    Nov 19 '18 at 23:30











  • Do you want to rename files, or do you want to modify the content of files? Those are two entirely different operations.

    – Ansgar Wiechers
    Nov 20 '18 at 0:32













  • Word and Excel documents are stored in a proprietary XML type format. You really can't edit the contents of these documents with powershell. Take a look at MS Office Interop. docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…

    – P.Brian.Mackey
    Nov 20 '18 at 4:03











  • @AnsgarWiechers modify the content. Example : change a person name for a number in all of the files that have this persons name

    – user91
    Nov 20 '18 at 12:01











  • If you want to modify the content of files the way to do that depends on the file type as Lee_Dailey already pointed out. Not all files are plaintext files (MS Office files specifically aren't).

    – Ansgar Wiechers
    Nov 20 '18 at 13:49














  • 1





    you are going to have to do things differently. [grin] PoSh cannot directly edit word docs or excel spreadsheets. you can install a PoSh module to handle the spreadsheets [i think ImportExcel is the name of one such]. to edit the MSWord docs will require using COM to open MSWord and control it. look up using COM objects with powershell. ///// as an aside, the PSPath parameter is not the one that is usually recommended for what you are doing. instead use the .FullName property.

    – Lee_Dailey
    Nov 19 '18 at 23:30











  • Do you want to rename files, or do you want to modify the content of files? Those are two entirely different operations.

    – Ansgar Wiechers
    Nov 20 '18 at 0:32













  • Word and Excel documents are stored in a proprietary XML type format. You really can't edit the contents of these documents with powershell. Take a look at MS Office Interop. docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…

    – P.Brian.Mackey
    Nov 20 '18 at 4:03











  • @AnsgarWiechers modify the content. Example : change a person name for a number in all of the files that have this persons name

    – user91
    Nov 20 '18 at 12:01











  • If you want to modify the content of files the way to do that depends on the file type as Lee_Dailey already pointed out. Not all files are plaintext files (MS Office files specifically aren't).

    – Ansgar Wiechers
    Nov 20 '18 at 13:49








1




1





you are going to have to do things differently. [grin] PoSh cannot directly edit word docs or excel spreadsheets. you can install a PoSh module to handle the spreadsheets [i think ImportExcel is the name of one such]. to edit the MSWord docs will require using COM to open MSWord and control it. look up using COM objects with powershell. ///// as an aside, the PSPath parameter is not the one that is usually recommended for what you are doing. instead use the .FullName property.

– Lee_Dailey
Nov 19 '18 at 23:30





you are going to have to do things differently. [grin] PoSh cannot directly edit word docs or excel spreadsheets. you can install a PoSh module to handle the spreadsheets [i think ImportExcel is the name of one such]. to edit the MSWord docs will require using COM to open MSWord and control it. look up using COM objects with powershell. ///// as an aside, the PSPath parameter is not the one that is usually recommended for what you are doing. instead use the .FullName property.

– Lee_Dailey
Nov 19 '18 at 23:30













Do you want to rename files, or do you want to modify the content of files? Those are two entirely different operations.

– Ansgar Wiechers
Nov 20 '18 at 0:32







Do you want to rename files, or do you want to modify the content of files? Those are two entirely different operations.

– Ansgar Wiechers
Nov 20 '18 at 0:32















Word and Excel documents are stored in a proprietary XML type format. You really can't edit the contents of these documents with powershell. Take a look at MS Office Interop. docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…

– P.Brian.Mackey
Nov 20 '18 at 4:03





Word and Excel documents are stored in a proprietary XML type format. You really can't edit the contents of these documents with powershell. Take a look at MS Office Interop. docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…

– P.Brian.Mackey
Nov 20 '18 at 4:03













@AnsgarWiechers modify the content. Example : change a person name for a number in all of the files that have this persons name

– user91
Nov 20 '18 at 12:01





@AnsgarWiechers modify the content. Example : change a person name for a number in all of the files that have this persons name

– user91
Nov 20 '18 at 12:01













If you want to modify the content of files the way to do that depends on the file type as Lee_Dailey already pointed out. Not all files are plaintext files (MS Office files specifically aren't).

– Ansgar Wiechers
Nov 20 '18 at 13:49





If you want to modify the content of files the way to do that depends on the file type as Lee_Dailey already pointed out. Not all files are plaintext files (MS Office files specifically aren't).

– Ansgar Wiechers
Nov 20 '18 at 13:49












3 Answers
3






active

oldest

votes


















1














As @lee_Daily pointed out you would need to have different code to perform a find and replace in different file types. Here is an example of how you could go about doing that:



$objWord = New-Object -comobject Word.Application  
$objWord.Visible = $false

foreach ( $file in (Get-ChildItem . -r ) ) {
Switch ( $file.Extension ) {
".config" {
(Get-Content $file.FullName) |
Foreach-Object { $_ -replace " JOHN ", "123" } |
Set-Content $file.FullName
}
{('.doc') -or ('.docx')} {
### Replace in word document using $file.fullname as the target
}
{'.xlsx'} {
### Replace in spreadsheet using $file.fullname as the target
}
}
}


For the actual code to perform the find and replace, i would suggest com objects for both.



Example of word find and replace https://codereview.stackexchange.com/questions/174455/powershell-script-to-find-and-replace-in-word-document-including-header-footer



Example of excel find and replace Search & Replace in Excel without looping?



I would suggest learning the ImportExcel module too, it is a great tool which i use a lot.






share|improve this answer


























  • Where would you include the folder path ?

    – user91
    Nov 20 '18 at 12:03











  • (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

    – Owain Esau
    Nov 20 '18 at 12:13













  • Should I stick with Windows power shell or maybe try to implement into a C# language ?

    – user91
    Nov 20 '18 at 12:23



















0














For Word Document : This is what I'm using. Just can't figure out how this script could also change Header and Footer in a Word Document



$objWord = New-Object -comobject Word.Application  
$objWord.Visible = $false

$list = Get-ChildItem "C:Users*.*" -Include *.doc*
foreach($item in $list){
$objDoc = $objWord.Documents.Open($item.FullName,$true)

$objSelection = $objWord.Selection
$wdFindContinue = 1
$FindText = " BLAH "
$MatchCase = $False
$MatchWholeWord = $true
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $wdFindContinue
$Format = $False
$wdReplaceNone = 0
$ReplaceWith = "help "
$wdFindContinue = 1
$ReplaceAll = 2

$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
$Wrap,$Format,$ReplaceWith,$ReplaceAll)
$objDoc.Save()
$objDoc.Close()
}
$objWord.Quit()





share|improve this answer































    -1














    What If I try to run on C# ? Is anything else missing?



     }
    string rootfolder = @"C:Temp";
    string files = Directory.GetFiles(rootfolder, "*.*",SearchOption.AllDirectories);
    foreach (string file in files)
    { try
    { string contents = File.ReadAllText(file);
    contents = contents.Replace(@"Text to find", @"Replacement text");
    // Make files writable
    File.SetAttributes(file, FileAttributes.Normal);

    File.WriteAllText(file, contents);
    }
    catch (Exception ex)
    { Console.WriteLine(ex.Message);
    }
    }





    share|improve this answer
























    • Switching to a different programming language doesn't magically allow you to treat binary files as text files.

      – Ansgar Wiechers
      Nov 20 '18 at 13:50











    • I understand that but what you think would be the best approach

      – user91
      Nov 20 '18 at 15:54











    • PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

      – Owain Esau
      Nov 20 '18 at 23:07











    • @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

      – user91
      Nov 21 '18 at 12:01













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    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%2fstackoverflow.com%2fquestions%2f53383858%2fwindows-power-shell-rename-files%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    As @lee_Daily pointed out you would need to have different code to perform a find and replace in different file types. Here is an example of how you could go about doing that:



    $objWord = New-Object -comobject Word.Application  
    $objWord.Visible = $false

    foreach ( $file in (Get-ChildItem . -r ) ) {
    Switch ( $file.Extension ) {
    ".config" {
    (Get-Content $file.FullName) |
    Foreach-Object { $_ -replace " JOHN ", "123" } |
    Set-Content $file.FullName
    }
    {('.doc') -or ('.docx')} {
    ### Replace in word document using $file.fullname as the target
    }
    {'.xlsx'} {
    ### Replace in spreadsheet using $file.fullname as the target
    }
    }
    }


    For the actual code to perform the find and replace, i would suggest com objects for both.



    Example of word find and replace https://codereview.stackexchange.com/questions/174455/powershell-script-to-find-and-replace-in-word-document-including-header-footer



    Example of excel find and replace Search & Replace in Excel without looping?



    I would suggest learning the ImportExcel module too, it is a great tool which i use a lot.






    share|improve this answer


























    • Where would you include the folder path ?

      – user91
      Nov 20 '18 at 12:03











    • (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

      – Owain Esau
      Nov 20 '18 at 12:13













    • Should I stick with Windows power shell or maybe try to implement into a C# language ?

      – user91
      Nov 20 '18 at 12:23
















    1














    As @lee_Daily pointed out you would need to have different code to perform a find and replace in different file types. Here is an example of how you could go about doing that:



    $objWord = New-Object -comobject Word.Application  
    $objWord.Visible = $false

    foreach ( $file in (Get-ChildItem . -r ) ) {
    Switch ( $file.Extension ) {
    ".config" {
    (Get-Content $file.FullName) |
    Foreach-Object { $_ -replace " JOHN ", "123" } |
    Set-Content $file.FullName
    }
    {('.doc') -or ('.docx')} {
    ### Replace in word document using $file.fullname as the target
    }
    {'.xlsx'} {
    ### Replace in spreadsheet using $file.fullname as the target
    }
    }
    }


    For the actual code to perform the find and replace, i would suggest com objects for both.



    Example of word find and replace https://codereview.stackexchange.com/questions/174455/powershell-script-to-find-and-replace-in-word-document-including-header-footer



    Example of excel find and replace Search & Replace in Excel without looping?



    I would suggest learning the ImportExcel module too, it is a great tool which i use a lot.






    share|improve this answer


























    • Where would you include the folder path ?

      – user91
      Nov 20 '18 at 12:03











    • (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

      – Owain Esau
      Nov 20 '18 at 12:13













    • Should I stick with Windows power shell or maybe try to implement into a C# language ?

      – user91
      Nov 20 '18 at 12:23














    1












    1








    1







    As @lee_Daily pointed out you would need to have different code to perform a find and replace in different file types. Here is an example of how you could go about doing that:



    $objWord = New-Object -comobject Word.Application  
    $objWord.Visible = $false

    foreach ( $file in (Get-ChildItem . -r ) ) {
    Switch ( $file.Extension ) {
    ".config" {
    (Get-Content $file.FullName) |
    Foreach-Object { $_ -replace " JOHN ", "123" } |
    Set-Content $file.FullName
    }
    {('.doc') -or ('.docx')} {
    ### Replace in word document using $file.fullname as the target
    }
    {'.xlsx'} {
    ### Replace in spreadsheet using $file.fullname as the target
    }
    }
    }


    For the actual code to perform the find and replace, i would suggest com objects for both.



    Example of word find and replace https://codereview.stackexchange.com/questions/174455/powershell-script-to-find-and-replace-in-word-document-including-header-footer



    Example of excel find and replace Search & Replace in Excel without looping?



    I would suggest learning the ImportExcel module too, it is a great tool which i use a lot.






    share|improve this answer















    As @lee_Daily pointed out you would need to have different code to perform a find and replace in different file types. Here is an example of how you could go about doing that:



    $objWord = New-Object -comobject Word.Application  
    $objWord.Visible = $false

    foreach ( $file in (Get-ChildItem . -r ) ) {
    Switch ( $file.Extension ) {
    ".config" {
    (Get-Content $file.FullName) |
    Foreach-Object { $_ -replace " JOHN ", "123" } |
    Set-Content $file.FullName
    }
    {('.doc') -or ('.docx')} {
    ### Replace in word document using $file.fullname as the target
    }
    {'.xlsx'} {
    ### Replace in spreadsheet using $file.fullname as the target
    }
    }
    }


    For the actual code to perform the find and replace, i would suggest com objects for both.



    Example of word find and replace https://codereview.stackexchange.com/questions/174455/powershell-script-to-find-and-replace-in-word-document-including-header-footer



    Example of excel find and replace Search & Replace in Excel without looping?



    I would suggest learning the ImportExcel module too, it is a great tool which i use a lot.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 20 '18 at 4:46

























    answered Nov 20 '18 at 0:33









    Owain EsauOwain Esau

    886718




    886718













    • Where would you include the folder path ?

      – user91
      Nov 20 '18 at 12:03











    • (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

      – Owain Esau
      Nov 20 '18 at 12:13













    • Should I stick with Windows power shell or maybe try to implement into a C# language ?

      – user91
      Nov 20 '18 at 12:23



















    • Where would you include the folder path ?

      – user91
      Nov 20 '18 at 12:03











    • (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

      – Owain Esau
      Nov 20 '18 at 12:13













    • Should I stick with Windows power shell or maybe try to implement into a C# language ?

      – user91
      Nov 20 '18 at 12:23

















    Where would you include the folder path ?

    – user91
    Nov 20 '18 at 12:03





    Where would you include the folder path ?

    – user91
    Nov 20 '18 at 12:03













    (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

    – Owain Esau
    Nov 20 '18 at 12:13







    (Get-ChildItem . -r ) the . is the current folder, i just used your example. Just change it to what you want.

    – Owain Esau
    Nov 20 '18 at 12:13















    Should I stick with Windows power shell or maybe try to implement into a C# language ?

    – user91
    Nov 20 '18 at 12:23





    Should I stick with Windows power shell or maybe try to implement into a C# language ?

    – user91
    Nov 20 '18 at 12:23













    0














    For Word Document : This is what I'm using. Just can't figure out how this script could also change Header and Footer in a Word Document



    $objWord = New-Object -comobject Word.Application  
    $objWord.Visible = $false

    $list = Get-ChildItem "C:Users*.*" -Include *.doc*
    foreach($item in $list){
    $objDoc = $objWord.Documents.Open($item.FullName,$true)

    $objSelection = $objWord.Selection
    $wdFindContinue = 1
    $FindText = " BLAH "
    $MatchCase = $False
    $MatchWholeWord = $true
    $MatchWildcards = $False
    $MatchSoundsLike = $False
    $MatchAllWordForms = $False
    $Forward = $True
    $Wrap = $wdFindContinue
    $Format = $False
    $wdReplaceNone = 0
    $ReplaceWith = "help "
    $wdFindContinue = 1
    $ReplaceAll = 2

    $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
    $MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
    $Wrap,$Format,$ReplaceWith,$ReplaceAll)
    $objDoc.Save()
    $objDoc.Close()
    }
    $objWord.Quit()





    share|improve this answer




























      0














      For Word Document : This is what I'm using. Just can't figure out how this script could also change Header and Footer in a Word Document



      $objWord = New-Object -comobject Word.Application  
      $objWord.Visible = $false

      $list = Get-ChildItem "C:Users*.*" -Include *.doc*
      foreach($item in $list){
      $objDoc = $objWord.Documents.Open($item.FullName,$true)

      $objSelection = $objWord.Selection
      $wdFindContinue = 1
      $FindText = " BLAH "
      $MatchCase = $False
      $MatchWholeWord = $true
      $MatchWildcards = $False
      $MatchSoundsLike = $False
      $MatchAllWordForms = $False
      $Forward = $True
      $Wrap = $wdFindContinue
      $Format = $False
      $wdReplaceNone = 0
      $ReplaceWith = "help "
      $wdFindContinue = 1
      $ReplaceAll = 2

      $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
      $MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
      $Wrap,$Format,$ReplaceWith,$ReplaceAll)
      $objDoc.Save()
      $objDoc.Close()
      }
      $objWord.Quit()





      share|improve this answer


























        0












        0








        0







        For Word Document : This is what I'm using. Just can't figure out how this script could also change Header and Footer in a Word Document



        $objWord = New-Object -comobject Word.Application  
        $objWord.Visible = $false

        $list = Get-ChildItem "C:Users*.*" -Include *.doc*
        foreach($item in $list){
        $objDoc = $objWord.Documents.Open($item.FullName,$true)

        $objSelection = $objWord.Selection
        $wdFindContinue = 1
        $FindText = " BLAH "
        $MatchCase = $False
        $MatchWholeWord = $true
        $MatchWildcards = $False
        $MatchSoundsLike = $False
        $MatchAllWordForms = $False
        $Forward = $True
        $Wrap = $wdFindContinue
        $Format = $False
        $wdReplaceNone = 0
        $ReplaceWith = "help "
        $wdFindContinue = 1
        $ReplaceAll = 2

        $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
        $MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
        $Wrap,$Format,$ReplaceWith,$ReplaceAll)
        $objDoc.Save()
        $objDoc.Close()
        }
        $objWord.Quit()





        share|improve this answer













        For Word Document : This is what I'm using. Just can't figure out how this script could also change Header and Footer in a Word Document



        $objWord = New-Object -comobject Word.Application  
        $objWord.Visible = $false

        $list = Get-ChildItem "C:Users*.*" -Include *.doc*
        foreach($item in $list){
        $objDoc = $objWord.Documents.Open($item.FullName,$true)

        $objSelection = $objWord.Selection
        $wdFindContinue = 1
        $FindText = " BLAH "
        $MatchCase = $False
        $MatchWholeWord = $true
        $MatchWildcards = $False
        $MatchSoundsLike = $False
        $MatchAllWordForms = $False
        $Forward = $True
        $Wrap = $wdFindContinue
        $Format = $False
        $wdReplaceNone = 0
        $ReplaceWith = "help "
        $wdFindContinue = 1
        $ReplaceAll = 2

        $a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, `
        $MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,`
        $Wrap,$Format,$ReplaceWith,$ReplaceAll)
        $objDoc.Save()
        $objDoc.Close()
        }
        $objWord.Quit()






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 12:06









        user91user91

        307




        307























            -1














            What If I try to run on C# ? Is anything else missing?



             }
            string rootfolder = @"C:Temp";
            string files = Directory.GetFiles(rootfolder, "*.*",SearchOption.AllDirectories);
            foreach (string file in files)
            { try
            { string contents = File.ReadAllText(file);
            contents = contents.Replace(@"Text to find", @"Replacement text");
            // Make files writable
            File.SetAttributes(file, FileAttributes.Normal);

            File.WriteAllText(file, contents);
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message);
            }
            }





            share|improve this answer
























            • Switching to a different programming language doesn't magically allow you to treat binary files as text files.

              – Ansgar Wiechers
              Nov 20 '18 at 13:50











            • I understand that but what you think would be the best approach

              – user91
              Nov 20 '18 at 15:54











            • PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

              – Owain Esau
              Nov 20 '18 at 23:07











            • @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

              – user91
              Nov 21 '18 at 12:01


















            -1














            What If I try to run on C# ? Is anything else missing?



             }
            string rootfolder = @"C:Temp";
            string files = Directory.GetFiles(rootfolder, "*.*",SearchOption.AllDirectories);
            foreach (string file in files)
            { try
            { string contents = File.ReadAllText(file);
            contents = contents.Replace(@"Text to find", @"Replacement text");
            // Make files writable
            File.SetAttributes(file, FileAttributes.Normal);

            File.WriteAllText(file, contents);
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message);
            }
            }





            share|improve this answer
























            • Switching to a different programming language doesn't magically allow you to treat binary files as text files.

              – Ansgar Wiechers
              Nov 20 '18 at 13:50











            • I understand that but what you think would be the best approach

              – user91
              Nov 20 '18 at 15:54











            • PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

              – Owain Esau
              Nov 20 '18 at 23:07











            • @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

              – user91
              Nov 21 '18 at 12:01
















            -1












            -1








            -1







            What If I try to run on C# ? Is anything else missing?



             }
            string rootfolder = @"C:Temp";
            string files = Directory.GetFiles(rootfolder, "*.*",SearchOption.AllDirectories);
            foreach (string file in files)
            { try
            { string contents = File.ReadAllText(file);
            contents = contents.Replace(@"Text to find", @"Replacement text");
            // Make files writable
            File.SetAttributes(file, FileAttributes.Normal);

            File.WriteAllText(file, contents);
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message);
            }
            }





            share|improve this answer













            What If I try to run on C# ? Is anything else missing?



             }
            string rootfolder = @"C:Temp";
            string files = Directory.GetFiles(rootfolder, "*.*",SearchOption.AllDirectories);
            foreach (string file in files)
            { try
            { string contents = File.ReadAllText(file);
            contents = contents.Replace(@"Text to find", @"Replacement text");
            // Make files writable
            File.SetAttributes(file, FileAttributes.Normal);

            File.WriteAllText(file, contents);
            }
            catch (Exception ex)
            { Console.WriteLine(ex.Message);
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 '18 at 12:15









            user91user91

            307




            307













            • Switching to a different programming language doesn't magically allow you to treat binary files as text files.

              – Ansgar Wiechers
              Nov 20 '18 at 13:50











            • I understand that but what you think would be the best approach

              – user91
              Nov 20 '18 at 15:54











            • PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

              – Owain Esau
              Nov 20 '18 at 23:07











            • @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

              – user91
              Nov 21 '18 at 12:01





















            • Switching to a different programming language doesn't magically allow you to treat binary files as text files.

              – Ansgar Wiechers
              Nov 20 '18 at 13:50











            • I understand that but what you think would be the best approach

              – user91
              Nov 20 '18 at 15:54











            • PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

              – Owain Esau
              Nov 20 '18 at 23:07











            • @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

              – user91
              Nov 21 '18 at 12:01



















            Switching to a different programming language doesn't magically allow you to treat binary files as text files.

            – Ansgar Wiechers
            Nov 20 '18 at 13:50





            Switching to a different programming language doesn't magically allow you to treat binary files as text files.

            – Ansgar Wiechers
            Nov 20 '18 at 13:50













            I understand that but what you think would be the best approach

            – user91
            Nov 20 '18 at 15:54





            I understand that but what you think would be the best approach

            – user91
            Nov 20 '18 at 15:54













            PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

            – Owain Esau
            Nov 20 '18 at 23:07





            PowerShell is more than Ok for this, and i believe PowerShell and C# use the same method for office integration. Could be wrong, dont know C#.

            – Owain Esau
            Nov 20 '18 at 23:07













            @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

            – user91
            Nov 21 '18 at 12:01







            @OwainEsau . I'm using powershell at the moment , I was able to find and figure out for Word Documents, but it does not change the file name and Header nd Footer of the file

            – user91
            Nov 21 '18 at 12:01




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • 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%2fstackoverflow.com%2fquestions%2f53383858%2fwindows-power-shell-rename-files%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







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini