1

I have a simple powershell function where I provide the log type and event and it scans all of our SQL servers. it works except the host name is returned as hostname.domain.local. I want it to return just the host name. I've tried machinename.split('.') and substring and it won't work. I've tried putting the select-object into a separate variable and was going to join it with the rest of the columns, but it takes too long to run.

Here is my sample scrap code i'm testing with before I change my function along with the commented out parts that didn't work. Looked around and found lots of resources about the commands, but they don't work when I try to use them in my script.

The error I keep getting is A positional parameter cannot be found that accepts argument '. '.

$servers = Get-Content -literalpath   "C:\temp\sql_servers3.txt" 
#$server
#$result = 
ForEach($box in $servers) {Get-Eventlog -ComputerName $box -LogName 
application -After 1-4-2018 -Entrytype Error | Where {$_.source -notin 
'Perfnet','Perflib', 'ntfs', 'vss'}| select-object -property MachineName}  
#$result_Host_name = select-object -inputobject $result -property 
 'MachineName'
 #'TimeGenerated', 'MachineName'.Split('.')[1], 'EventID','message'}
 #| Where {$_.source -notin 'Perfnet','Perflib', 'ntfs', 'vss'} 0
 #return $result_Host_name
2
  • Give an example of a line from your text file and what you are trying to extract as the computer name. Commented Jan 5, 2018 at 19:02
  • The text file is just a list of servers that I'm scanning. I'm looping through it and running get-eventlog for each one. The default doesn't give me the columns I want so I added a select-object at the end to output four columns including MachineName. that one outputs as a full DNS name as hostname.domain.local and I just wanted the hostname part. Commented Jan 5, 2018 at 19:10

1 Answer 1

1

What you are looking for is a "Calculated Property" when using Select-Object.

| Select-Object @{n='HostName';e={($_.MachineName -split '\.')[0]}}
Sign up to request clarification or add additional context in comments.

3 Comments

That took the entire column out of the result set.
@Alen What do you mean took the entire column out of the result set? It should have returned only the Hostnames. IF you want all of the other properties you can put add a * (or whichever properties you want comma delimited) e.g. | Select-Object *,@{n='HostName';e={($_.MachineName -split '\.')[0]}} and this will return all of the properties plus the hostname
sorry, made a mistake with brackets. Looks like it's working and i'm testing now with your code plus the three other columns I need

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.