在PowerShell

时间:2016-08-23 21:35:19

标签: powershell powershell-v2.0

我有以下脚本:

$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) | 
        Foreach-Object {$_ -replace "my-project-name", '$appNameDashCased$'} |
        Set-Content $file.PSPath    

    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) | 
        Foreach-Object {$_ -replace "MyProjectName", '$appNameCamelCased$'} |
        Set-Content $file.PSPath    

    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) | 
        Foreach-Object {$_ -replace "myProjectName", '$appNamePascalCased$'} |
        Set-Content $file.PSPath    
}

它需要一个文件并进行一些替换,然后保存文件。然后它采用相同的文件并进行更多更换,然后再次保存文件。然后再做一次。

这有效,但似乎效率低下。

有没有办法完成所有替换,然后保存文件一次?

(如果可能的话,我宁愿保持PowerShell的可读风格。)

2 个答案:

答案 0 :(得分:3)

这可以做到,而且实际上比你正在做的要简单得多。您可以链接-Replace命令:

$allFiles = Get-ChildItem "./" -Recurse | Where { ($_.Extension -eq ".ts")}
foreach($file in $allFiles)
{
    # Find and replace the dash cased the contents of the files
    (Get-Content $file.PSPath) -replace "my-project-name", '$appNameDashCased$' -replace "StringB", '$SecondReplacement$' -replace "StringC", '$ThirdReplacement$' | Set-Content $file.PSPath
}

答案 1 :(得分:2)

当然,只需将您的替换链接到>>> playerhp = 100 >>> def attack1(): ... global playerhp ... playerhp -= 17 ... >>> attack1() >>> playerhp 83 块内:

ForEach-Object