如何更好地执行此powershell脚本?
当我将FenrirFS配置文件移动到另一个配置文件时,目录中的路径就会出错。 所以我决定制作一个ps脚本来解决这个问题如何更好地执行此powershell脚本?,powershell,Powershell,当我将FenrirFS配置文件移动到另一个配置文件时,目录中的路径就会出错。 所以我决定制作一个ps脚本来解决这个问题 $wdir = "files" # constant part of path $path = $PSScriptRoot # path to script $pfix = "Target=" # prefix of path $files = Get-ChildItem -Path $path -Filter *.
$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++
}
}
这是工作,但我有很多文件,我应该替换它们。
而且$filec |设置内容$file
有点愚蠢,因为我只需要替换一行。
文件示例:
Target=E:\home\prj\polygon\ps\files\NoDigital\godTech_2.JPG
DisplayName=godTech_2.JPG
WorkDir=
Arguments=
ShowCmd=0
ps脚本位于带有别名的目录中
p、 美国powershell 5.1您可以使用速度更快的
开关
:
$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
}
您可以使用更快的
开关
:
$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
}
请给我们看(部分)这样一个文件,其中包含要替换的行和所需输出的示例。我想要的是:
Target=E:\home\prj\polygon\ps\files\NoDigital\godTech\u 2.JPG
edit to:Target=E:\“new\u directory\u to\u profile”\files\NoDigital\godTech\u 2.JPG
“$filec |设置内容$file有点愚蠢,因为我只需要替换一行”-不,这实际上是正确的方法-底层文件系统不知道“行”是什么,该文件只是磁盘上的一个长字符串。如果您想查看代码,请随时发布给我们(部分)这样一个包含要替换的行和所需输出的示例的文件我想要的是:Target=E:\home\prj\polygon\ps\files\NoDigital\godTech\u 2.JPG
edit to:Target=E:\“new\u directory\u to\u profile”\files\NoDigital\godTech\u 2.JPG
“$filec\124;设置内容$file有点愚蠢,因为我只需要替换一行-不,这实际上是正确的方法-底层文件系统不知道“行”是什么,文件只是磁盘上的一个长字符串。如果您想查看代码,请随意发表文章,这样做效果很好,但是switch在这个上下文中意味着什么?@KirillMoskalew开关逐行循环通过文件,并在每个文件上执行一个tegex命令。所有这些高速运行都很好,但在这种情况下,switch意味着什么?@KirillMoskalew开关一行一行地在文件中循环,并在每个文件上执行一个tegex COMORE。所有这些高速