Assign output to variable and checking if string exists in it only work after outfile

Hey guys,
I’m having some issues with assigning a command output to a variable and then checking if a string is present in that variable.

Basically what I’m trying to do is get a list of my computer’s static route and check if a list of IPs I have is present in the static routes.

$NSLookup = (nslookup  |  Select-String -Pattern "\d{1,3}(\.\d{1,3}){3}" -AllMatches).Matches.Value | where { $_ -notmatch ""}
Get-NetRoute | where{$_.NextHop -eq ''} | select DestinationPrefix | ft -HideTableHeaders | Out-File 'C:\routes.txt'
$StaticRoute = Get-Content 'C:\routes.txt'
$Mask = x.x.x.x
$Gateway = x.x.x.x

foreach($IP in $NSLookup){
if($StaticRoute -match $IP ){
Write-Host $IP "Already in static addresses"

route add -p $IP mask $Mask $Gateway
Write-Host $IP "Added to static route"

As you can see from the script i’m outputting the Get-NetRoute command to txt and then extracting the content out of it - this works fine.
What I was trying to do was to assign the Get-NetRoute command directly to the variable and checking if static routes variable contains that IP.For some reason It was not able to give me correct results and was always giving me that static routes does not contain this IP even if it does.

Thanks in advance


This is a bit hard to troubleshoot because you’ve posted a working script :slight_smile:

Can you show us how you were assigning the output from Get-NetRoute to the variable and maybe we can tell you why it wasn’t working? If I had to guess, you were trying to use ft or Format-Table and that broke it.

If you change it to the line below, it should work:

$staticRoute = Get-NetRoute | Where-Object {$_.NextHop -eq ''} | Select-Object DestinationPrefix

If you want to remove the header from the variable use:

$staticRoute = Get-NetRoute | Where-Object {$_.NextHop -eq ''} | Select-Object  -ExpandProperty DestinationPrefix

Haha yeah I guess.I will try to find the draft of the not working one and post it.
But i’m pretty sure it was looking like this:

$StaticRoute = Get-NetRoute | where{$_.NextHop -eq ''} | select DestinationPrefix | ft -HideTableHeaders 

I will check if the format table is the reason this was not working well but any idea why is it so?

The Format cmdlets add special formatting that’s meant for on-screen display. They can also be used with some of the Out cmdlets but you can’t pipe them to other cmdlets and you’ll get unexpected results when you assign them to a variable.


Get-NetRoute | Where-Object {$_.NextHop -eq ''} | 
    Select-Object DestinationPrefix | ConvertTo-Html


Get-NetRoute | Where-Object {$_.NextHop -eq ''} | 
    Select-Object DestinationPrefix | Format-Table -HideTableHeaders | ConvertTo-Html

Thank you very much for the explanation this is now working great.
I’ve used the line you provided in your first comment removing the header.


1 Like