Windows Power Shell重命名文件

时间:2018-11-19 22:59:32

标签: powershell scripting

我是脚本的新手,这是我的任务:

包含X个文件的文件夹。每个文件都包含一些Word文档,Excel工作表等。在这些文件中,有一个客户名称,我需要分配一个ID号。

此更改将影响此文件夹中包含该客户端名称的所有文件。

如何使用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
}   

这是正确的方法吗?

3 个答案:

答案 0 :(得分:1)

正如@lee_Daily指出的那样,您需要使用不同的代码来执行查找和替换不同文件类型的操作。这是一个有关如何执行此操作的示例:

$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
        }
    }
}

对于执行查找和替换的实际代码,我建议两者都使用com对象。

查找和替换单词的示例 https://codereview.stackexchange.com/questions/174455/powershell-script-to-find-and-replace-in-word-document-including-header-footer

excel查找和替换的示例 Search & Replace in Excel without looping?

我也建议学习ImportExcel模块,这是我经常使用的很棒的工具。

答案 1 :(得分:0)

对于Word文档:这就是我正在使用的。只是无法弄清楚此脚本还可以如何更改Word文档中的页眉和页脚

$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()

答案 2 :(得分:-1)

如果我尝试在C#上运行怎么办?还有其他东西吗?

 }
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);
     }
   }