在文本文件中查找字符串,并在末尾附加文本

时间:2018-10-03 22:51:35

标签: powershell

我的Firefox模块有问题。要解决此问题,我需要将文本追加到每个用户的Firefox配置文件下找到的文本文件中。

我可以使用以下powershell脚本将新的文本文件复制到每个用户个人资料:

    # Check to see if AWP is actually installed

    $chkAWPExists = "C:\Program Files\Middleware Directory\Middleware"
    $aWPExists = Test-Path $chkAWPExists

    # If AWP Exists copy the pkcs11.txt file to all Firefox Profiles found.

    If ($aWPExists -eq $True) {
        Write-Log "AWP Exists. Copying pkcs11.txt to all firefox profiles"
        Get-ChildItem -Path 'C:\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles\*\pkcs11.txt' |
        ForEach-Object {
            Copy-Item -Path 'pkcs11.txt' -Destination $_.DirectoryName
        }
        }
    else {
        Write-Log "AWP doesn't seem to be installed. Please install Oberthur Authentic web pack before activating this module."
        ExitCode 1
    }

但是我的问题是每个文本文件似乎对每个用户都有唯一的信息。仅将新的文本行添加到txt文件末尾可能是有道理的。

有人可以帮我弄清楚如何将文本添加到每个用户个人资料并遍历他们吗?

这是我需要添加两行文字的示例:

library=etpkcs11.dll 
name=eToken PKCS#11 Module

任何帮助将不胜感激。

运行脚本后,我也想不出如何解决新配置文件。但这是另一场战斗。

1 个答案:

答案 0 :(得分:1)

这应该有效:

$toAppend = "
library=etpkcs11.dll 
name=eToken PKCS#11 Module
"

# Check to see if AWP is actually installed

$chkAWPExists = "C:\Program Files\Middleware Directory\Middleware"
$aWPExists = Test-Path $chkAWPExists

# If AWP Exists copy the pkcs11.txt file to all Firefox Profiles found.

If ($aWPExists -eq $True) {
    Write-Log "AWP Exists. Copying pkcs11.txt to all firefox profiles"
    ForEach ($file in (Get-ChildItem -Path 'C:\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles\*\pkcs11.txt'))  {
        $toAppend | Out-File -Append $file -Encoding 'Ascii'
    }
}
else {
    Write-Log "AWP doesn't seem to be installed. Please install Oberthur Authentic web pack before activating this module."
    ExitCode 1
}

我更改的是以下代码部分(foreach循环):

Get-ChildItem -Path 'C:\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles\*\pkcs11.txt' |
ForEach-Object {
    Copy-Item -Path 'pkcs11.txt' -Destination $_.DirectoryName
}

收件人:

ForEach ($file in (Get-ChildItem -Path 'C:\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles\*\pkcs11.txt'))  {
            $toAppend | Out-File -Append $file -Encoding 'Ascii'

它没有将Get-Childitem调用传递给Foreach-Object,而是在foreach循环中调用Get-Childitem,使$ file成为特定文件的路径。

实际的附加只是将$ toAppend变量(在顶部定义)传递到Out-File -Append函数:

$toAppend | Out-File -Append $file