I have this file structure
In PowerShell my location is set to Folder
. SubSubFolders
has a lot of xml files, and I want to add a line there only if content of version.txt
file is a
and that line doesn't exist there already.
I was able to figure out how to change an xml file in particular SubSubFolder
, but I can't do it when I start in Folder
folder and and taking into consideration version
#here I need to add: only if version.txt content of xml file in parent folder is "a"
$files = Get-ChildItem -Filter *blah.xml -Recurse | Where{!(Select-String -SimpleMatch "AdditionalLine" -Path $_.fullname -Quiet)} | Format-Table FullName
foreach($file in $files)
{
(Get-Content $file.FullName | Foreach-Object { $_
if ($_ -match "AdditionalLineAfterThisLine")
{
"AdditionalLine"
}
}) | Set-Content $file.FullName
}
CodePudding user response:
If I understand you correctly, you're looking for the following:
$files = (
Get-ChildItem -Filter *blah.xml -Recurse |
Where-Object{
-not ($_ | Select-String -SimpleMatch "AdditionalLine" -Quiet) -and
(Get-Content -LiteralPath "$($_.DirectoryName)/../version.txt") -eq 'a'
}
).FullName
Note that the assumption is that the version.txt
file contains just one line. If it contains multiple lines, the -eq 'a'
operation would act as a filter and return all lines whose content is 'a'
, which in the implied Boolean context of -and
would yield $true
if one or more such lines, potentially among others, exist.