Powershell - error checking for find and replace (ForEach-Object) - powershell

I need to add error checking on the ForEach-Object part.
Currently, this code works to replace a value in a file. However, if it can't find the value, it doesn't seem to generate any error. I have done a try and catch but it just isn't working. I've searched for hours and tried all kinds of stuff ... any help?
I can do the command two different ways, not sure what is better or easier to add error checking on...
(Get-Content $file) | ForEach-Object { $_ -replace $replace, $with } | Set-Content $file
-OR-
ForEach-Object { (Get-Content $file) -replace $replace, $with } | Set-Content $file
Thank you.

finding nothing to replace is not an error, it just returns the original back. so check for it in an if statement, like:
foreach { $rep=$_ -replace $replace,$width; if ($_ -eq $rep) {...} }

Related

Dynamically replacing file content

I have to read one properties file (let's say prop.txt) and update it dynamically.
Content looks like this.
server.names=xyz[500],server2[500],test[500]
I wanted to replace the content anything after server.names= with correct values, e.g.:
server1.company.com[500],server2.company.com[500],server3.company.com[500]
I tried below command but it is replacing server.names=. I want to replace the values of server.names=
(Get-Content $path).Replace("server.names=",$NewServerNames) | Set-Content $path
Any idea how to replace the value of server.names=?
You were close, but your syntax is off. This solution utilizes regex to capture the original key:
$Pattern = 'server\.names='
Get-Content -Path $Path |
ForEach-Object {
If ($_ -match $Pattern)
{
$_ -replace "($Pattern).*","$1$NewServerNames"
}
Else
{
$_
}
} |
Set-Content -Path $Path

Delete lines from multiple textfiles in PowerShell

I am trying to delete lines with a defined content from multiple textfiles.
It works in the core, but it will rewrite every file even if no changes are made, which is not cool if you are just modifying 50 out of about 3000 logonscripts.
I even made a if statement but it seems like it doesn't work.
Alright this is what I already have:
#Here $varFind will be escaped from potential RegEx triggers.
$varFindEscaped = [regex]::Escape($varFind)
#Here the deletion happens.
foreach ($file in Get-ChildItem $varPath*$varEnding) {
$contentBefore = Get-Content $file
$contentAfter = Get-Content $file | Where-Object {$_ -notmatch $varFindEscaped}
if ($contentBefore -ne $contentAfter) {Set-Content $file $contentAfter}
}
What the variables mean:
$varPath is the path in which the logonscripts are.
$varEnding is the file ending of the files to modify.
$varFind is the string that triggers the deletion of the line.
Any help would be highly appreciated.
Greetings
Löwä Cent
You have to read the file regardless but some improvement on your change condition could help.
#Here the deletion happens.
foreach ($file in Get-ChildItem $varPath*$varEnding) {
$data = (Get-Content $file)
If($data -match $varFindEscaped){
$data | Where-Object {$_ -notmatch $varFindEscaped} | Set-Content $file
}
}
Read the file into $data. Check to see if the pattern $varFindEscaped is present in the file. If it is than filter out those matching the same pattern. Else we move onto the next file.

Removing line break powershell

I am having an issue with a line break in my data. The array was made with an out-string followed by -split. If you want to see that part of the script let me know.
foreach ($item in $array) {
"_"+$item+"_"
}
Output:
_
itemname_
Desired Output:
itemname
I've tried inserting:
$item.replace('`','')
Without any change. Any ideas?
Okay, I think this should work. I was under the impression you wanted those underscores in the result.
$array -replace "`n|`r"
By default, 'Get-Content' command has the default delimiter of a new line '\n'. Create a costume parameter and then do your replace command. Hope this helps.
Get-ChildItem | Get-Content -Delimiter "~" | foreach { $_ -replace "`r|`n","" }
Well how about applying mjolinor's code at the $item level, e.g.:
foreach ($item in $array) {
$item -replace '^|$','_'
}
Although I expect the same result you are already getting, there are newlines embedded in your string.
I'm not able to setup the same condition in $array myself, maybe you could post that code.
Does this work?:
foreach ($item in $array) {
$item.Trim() -replace '^|$','_'
}
foreach ($item in $array) {
"_"+$item.Trim()+"_"
}
Should do what you want.

Powershell V2 find and replace

I am trying to change dates programmatically in a file. The line I need to fix looks like this:
set ##dateto = '03/15/12'
I need to write a powershell V2 script that replaces what's inside the single quotes, and I have no idea how to do this.
The closest I've come looks like this:
gc $file | ? {$_ -match "set ##dateto ="} | % {$temp=$_.split("'");$temp[17]
=$CorrectedDate;$temp -join ","} | -outfile newfile.txt
Problems with this: It gives an error about the index 17 being out of range. Also, the outfile only contains one line (The unmodified line). I'd appreciate any help with this. Thanks!
You can do something like this ( though you may want to handle the corner cases) :
$CorrectedDate = '10/09/09'
gc $file | %{
if($_ -match "^set ##dateto = '(\d\d/\d\d/\d\d)'") {
$_ -replace $matches[1], $CorrectedDate;
}
else {
$_
}
} | out-file test2.txt
mv test2.txt $file -force

How do I add a simple search and replace to this loop in Powershell?

I wrote this so far, it runs through and does exactly what I want, now I'm stuck. I can't seem to get it to open the newly created $NOSPACE.shtml and replace a word with the variable $SPACE though. A little help please?
$CITYLIST=import-csv CityList.txt
$CITYLIST | FOREACH-OBJECT { $_ }
FOREACH ($Item in $CITYLIST) {
$Item.City
$NOSPACE=$Item.City.replace(" ","_")
$SPACE=$Item.City
Add-Content _citylist.shtml "`n<a class=`"cityareaslist`" href=`"`/$NOSPACE.shtml`"> $SPACE<`/a>" ; Copy-Item index.shtml "$NOSPACE.shtml"
}
(Get-Content "$NOSPACE.shtml") |
Foreach-Object {$_ -replace 'word',$SPACE} |
Set-Content "$NOSPACE.shtml"