【问题标题】:PowerShell - Creating a back up of a script then overwritingPowerShell - 创建脚本的备份然后覆盖
【发布时间】:2022-08-13 21:29:25
【问题描述】:

我想备份一个我拥有的脚本,然后将一个新字符串附加到文件中。每当我尝试创建备份时,我都无法再追加到文件中。

这是代码:

             #Back the file
              if (-NOT (Test-Path -Path $someFile\".bak\"))
              {
                 Copy-Item -Path $someFile -Destination $someFile\".bak\"
              }
                
            if (-NOT ($json.CaptureSettings.IncludeProcess))
            {   
               Set-Content $someFile -Value $(
               @(
                 switch -Wildcard -File $someFile{
                 \'#*\' { $_ }
                 default { break }
                 }
                 # Append the dummy process string to the file
                ) + \"`n`n# Dummy process inserted here\", \"`n EMPTY_PROCESS.EXE\"
               )
            }

我是 PowerShell 的新手,我不熟悉为什么它不会进入 Set-Content 函数。它将进入 if 语句,但不会对 Set-Content 执行任何操作。

编辑:我相信它没有找到任何带有 \'#*\' 的东西,尽管它以前工作过。

如果我不包含创建备份的前 4 行代码(第一个 if 语句),此函数将起作用。

  • @Daniel 你指定的是我的意图。我正在寻找解析文件,保留以 \'#\' 开头的每一行,然后附加虚拟进程行。

标签: powershell


【解决方案1】:

这个问题有点含糊,但如果我理解正确,您只想保留以# 开头的行,然后将新行附加到文件中。

在这种情况下,您可以这样做:

$newContent = switch -Wildcard -File $someFile {
    '#*' { $_ }   # keep all lines starting with #
}
Set-Content -Path $someFile
# Append the dummy process string to the file
Add-Content -Path $someFile -Value "`r`n# Dummy process inserted here", "`r`nEMPTY_PROCESS.EXE"

或者您也可以在不使用开关的情况下执行此操作:

$newContent = Get-Content -Path $someFile | Where-Object { $_ -like '#*' }
Set-Content -Path $someFile
# Append the dummy process string to the file
Add-Content -Path $someFile -Value "`r`n# Dummy process inserted here", "`r`nEMPTY_PROCESS.EXE"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-23
    • 2017-12-16
    • 1970-01-01
    • 2012-01-15
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多