简体   繁体   English

我怎样才能更好地完成这个 powershell 脚本?

[英]How I can do this powershell script better?

When I move FenrirFS profile to another, paths in directories become wrong.当我将 FenrirFS 配置文件移动到另一个配置文件时,目录中的路径会出错。 So I decided to make a ps script to resolve it.所以我决定制作一个ps脚本来解决它。

$wdir = "files"       # constant part of path
$path = $PSScriptRoot # path to script
$pfix = "Target="     # prefix of path

$files = Get-ChildItem -Path $path -Filter *.alias | Where { ! $_.PSIsContainer } | Select -Expand Name

foreach ($file in $files) 
{
    $filec = Get-Content $file
    $nlin = 0         # counter of line

    foreach ($line in $filec) 
    {
        if($line.Contains($pfix)) 
        {
            $nline = $pfix + $path + '\' + $wdir + ($line -split $wdir)[1]
            $filec[$nlin] = $filec[$nlin].replace($line,$nline)
            $filec | Set-Content $file
            break
        }
    $nlin++ 
    }
}

It's work, but I have a lot of files, which I should replace.这是工作,但我有很多文件,我应该替换。 And $filec | Set-Content $file$filec | Set-Content $file $filec | Set-Content $file a little bit dumby, cuz I need to replace only one line. $filec | Set-Content $file有点笨,因为我只需要替换一行。 Example of file:文件示例:

Target=E:\home\prj\polygon\ps\files\NoDigital\godTech_2.JPG
DisplayName=godTech_2.JPG
WorkDir=
Arguments=
ShowCmd=0

ps script is located in the directory with aliases. ps 脚本位于具有别名的目录中。

ps powershell 5.1 ps powershell 5.1

You could use the much faster switch for that:您可以为此使用更快的switch

$wdir = "files"       # constant part of path
$path = $PSScriptRoot # path to script
$pfix = "Target="     # prefix of path

$files = Get-ChildItem -Path $path -Filter '*.alias' -File | ForEach-Object {
    $content = switch -Regex -File $_.FullName {
        "^$pfix"  { 
            $oldPath = ($_ -split '=', 2)[-1].Trim()
            $childPath = Join-Path -Path $wdir -ChildPath ($oldPath -split $wdir, 2)[-1] 
            # output the new path
            "$pfix{0}" -f (Join-Path -Path $path -ChildPath $childPath)
        }
        default { $_ }
    }
    $content | Set-Content -Path $_.FullName -Force
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM