0

I'm trying to replace a hostname with an FQDN located anywhere in a specific file. The following works fine, unless the FQDN is already in the file. If FQDN is there, it adds a second domain name to the FQDN.

$test = Get-Content C:\temp\test.txt
$test -replace ($compname, $fqdn)

Essentially, I need to replace if, and only if, the string matches compname, but doesn't match FQDN.

Any suggestions? Thanks!

1
  • 1
    Remove the parentheses around $compname, $fqdn Commented Mar 5, 2020 at 16:56

3 Answers 3

2

Regex to the rescue!

"(computer)(?!\.contoso\.com)"

You want to match on "computer" name, and use negative look ahead to ignore ones that already have the FQDN portion.

$test = Get-Content C:\temp\test.txt
$test -replace "($compname)(?!\.contoso\.com)", $fqdn
Sign up to request clarification or add additional context in comments.

Comments

1

The first parameter is a regular expression, so you want to match on $compname that does not occur before the domain portion of the FQDN. You can achieve this with a Negative Lookahead:

$domain = [regex]::Escape( $fqdn.split( '.', 2 )[1] )
$test -replace "${compname}(?!${domain})", $fqdn

Let's break down what this does:

  • $domain = [regex]::Escape( $fqdn.split( '.', 2 )[1] ) - Extract the domain portion of the FQDN, and make sure it's escaped so no special characters are interpreted as regex syntax
  • "${compname}(?!\.${domain})" - Regex pattern to match on - let's break this down
    • ${compname} - Insert the $compname variable as part of the string
    • \. - Match on a literal .; the backslash is required as . is a special token (matches any character) when processing regular expressions
    • () - Grouped expression - let's also break this down
      • ?! - Negative lookahead operator, tells the grouped expression that this group cannot match after the preceeding expression. If matched, this group is discarded from the result.
      • ${domain} - Same as ${compname}, just inserting the variable into the expression

Comments

0

I figured out a way to overwrite the entire line, rather than replace comp name.

$match = $test | select-string -pattern "serverName"
$test -replace $match,"serverName = $fqdn" | set-content c:\temp\test.txt

This guarantees whatever the entry is will be overwritten by the FQDN.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.