Powershell: Display Errors from Resolve-DnsName - powershell

Good morning,
so i got a bunch of IPs and wanted to get the DNS Name,
so i tried this.
Select-String -Allmatches -pattern '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' |% { $_.Matches }| % { $_.Value }| select -Unique| %{Resolve-Dnsname -name $_}
This works, but when i output it to a file i only get the results where he could find an Hostname.
Is there a method to also display the errors.

I would probably do it this way:
Select-String -AllMatches -Pattern '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' |
Select-Object -ExpandProperty Matches |
Select-Object -ExpandProperty Value -Unique |
ForEach-Object {
$Resolve = $null
$Resolve = Resolve-DnsName -Name $_ -ErrorAction SilentlyContinue
[PSCustomObject]#{
IP = $_
Name = $Resolve.Name
Type = $Resolve.Type
TTL = $Resolve.TTL
Section = $Resolve.Section
NameHost = $Resolve.NameHost
}
}
You can specify whatever fields you want in the custom object. I have simply included the default properties that Resolve-DnsName outputs to the screen.
In general, Select-Object -ExpandProperty <property> performs better than ForEach-Object { $_.<property> }.
I'm fairly certain the code I have above will work, but there's an outside chance that this:
Select-Object -ExpandProperty Value -Unique |
May need to be this:
Select-Object -ExpandProperty Value |
Select-Object -Unique |

Related

powershell out-file how to rid of extra spaces on each line

I run this command and I get all computer hostnames in the names.txt file.
Each hostname in the file is on a separate line, but every hostname is followed with white spaces which cause an issue when I try to read this file. How can I output to this file without getting the white spaces on each line?
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | out-file -filepath C:\temp\names.txt
You have the problem that you don't just have names, you have objects with the property 'name', and you also have the problem that Out-File runs complex objects through some kind of formatting before sending them to the file.
To fix both, expand the name out to just text, and generally use Set-Content instead:
Get-ADComputer -filter * | Select-Object -ExpandProperty Name | Sort-Object | Set-Content C:\temp\names.txt
or in short form
Get-ADComputer -filter * | Select -Expand Name | Sort | sc C:\temp\names.txt
or
(Get-ADComputer -filter *).Name | sort | sc C:\temp\names.txt
expandproperty should get rid of the #()
Get-ADComputer -Filter * | sort Name | Select -expandproperty Name | %{ $_.TrimEnd(" ") } | out-file -filepath C:\temp\names
Untested no AD#home
Piping it through this should work (before piping to the out-file):
EDIT: Piping through % { $_.name } should convert #{name=VALUE} to VALUE:
% { $_ -replace ' +$','' } | % { $_.name }
Like this:
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | % { $_ -replace ' +$','' } | % { $_.name } | out-file -filepath C:\temp\names.txt

Loop through each item against a cmdlet

I have a list of port number and I want to see which program is using that port. I want to filter the Get-Networkstatistics cmdlet to show me only certain ports that are in the port.txt file. I modified the
Get-NetworkStatistics | Select-Object ComputerName, LocalPort, ProcessName
to loop through only the port numbers I provide. However, the $result variable is not storing anything and the output is null. What am I doing wrong?
$file = .\ports.txt
foreach ( $port in $file )
{
$result += Get-NetworkStatistics |
Select-Object ComputerName, LocalPort, ProcessName |
Where-Object {$_.LocalPort -eq $port}
}
$result | Export-Csv .\networkports.csv
You have to use the Get-Content cmdlet:
$file = Get-Content "path_to_ports.txt'
First of all, you want to filter before doing Select, that way you have to select lower objects.
$result = #() #array
foreach ( $port in $file )
{
$result += Get-NetworkStatistics | Where-Object {$_.LocalPort -eq $port} | Select-Object ComputerName, LocalPort, ProcessName
}
$result | Export-Csv .\networkports.csv
As for the actual problem itself, I believe it is due to scoping. You need to declare variable before the loop, so it is available in the loop, and after the loop.
The statement
$file = .\ports.txt
Doesn't read the file into the variable. Use Get-Content for that.
Also, you don't need a loop. Get-Content reads the input file into an array of strings, so you can use the -contains operator for checking if the list contains a given local port:
$ports = Get-Content '.\ports.txt'
Get-NetworkStatistics |
Where-Object { $ports -contains $_.LocalPort } |
Select-Object ComputerName, LocalPort, ProcessName |
Export-Csv '.\networkports.csv' -NoType
On PowerShell v3 or newer you can also use the -in operator, which feels a bit more "natural" to most users:
$ports = Get-Content '.\ports.txt'
Get-NetworkStatistics |
Where-Object { $_.LocalPort -in $ports } |
Select-Object ComputerName, LocalPort, ProcessName |
Export-Csv '.\networkports.csv' -NoType

New-Item : Access to the path is denied

I have a PowerShell script below
$ous = 'ou=office,dc=xxx,dc=com',`
'ou=shop0,dc=xxx,dc=com',`
'ou=shop1,dc=xxx,dc=com',`
'ou=shop2,dc=xxx,dc=com'
$outfile = 'c:\work\userinfo.csv'
New-Item -Force -type "file" -Path 'c:\work\userinfo.csv'
$ous | ForEach {
Get-ADUser -Filter * -SearchBase $_ |
Select-Object -Property CN,`
DisplayName,`
GivenName,`
Surname,`
SamAccountName,`
PasswordExpired,`
mail,`
Description,`
Office,`
EmployeeNumber,`
Title |
Sort-Object -Property Name |
export-csv -Append $outfile -NoTypeInformation
}
Then when I run it, I got error message "New-Item: access to the path c:\work\userinfo.csv" is denied.
What's the cause for this error?
Update:
In my case, somehow, PowerShell is case-sensitive....the output folder name is uppercase, in my script is lowercase, it works after I match them.
I am bypassing the reason for the error ( of which I'm not sure of the cause.). Another way to get what you want
each time I run script, I could get an fresh result without previous results
You just need to move the output code outside the loop and remove the append. Pipeline handles the Append for you.
$ous | ForEach {
Get-ADUser -Filter * -SearchBase $_ |
Select-Object -Property CN,`
DisplayName,`
GivenName,`
Surname,`
SamAccountName,`
PasswordExpired,`
mail,`
Description,`
Office,`
EmployeeNumber,`
Title
} | Sort-Object -Property Name |
export-csv -Append $outfile -NoTypeInformation
Noticed something
You are not calling all the properties you are using in your select statement. That should lead to some null columns in your output. I would update your code to something like this.
$props = "CN","DisplayName","GivenName","Surname","SamAccountName","PasswordExpired","mail","Description","Office","EmployeeNumber","Title"
$ous | ForEach-Object {
Get-ADUser -Filter * -SearchBase $_ -Properties $props | Select-Object $props
} | Sort-Object -Property Name |
export-csv $outfile -NoTypeInformation

List all Server Features/Roles in Powershell

So I have the following code to output all features and roles installed:
Import-Module ServerManager
$Arr = Get-WindowsFeature | Where-Object {$_.Installed -match “True”} | Select-Object -Property Name
$loopCount = $Arr.Count
For($i=0; $i -le $loopCount; $i++) {
Write-Host $Arr[$i]
}
However, the output is:
#{Name=Backup-Features}
#{Name=Backup}
#{Name=Backup-Tools}
How can I get rid of the # and {}'s ?
Use Select -ExpandProperty Name instead of Select -Property Name
Alternatively and also, I recommend using Foreach-Object instead of a C-style for loop.
Import-Module ServerManager
Get-WindowsFeature |
Where-Object {$_.Installed -match “True”} |
Select-Object -ExpandProperty Name |
Write-Host
Or
Import-Module ServerManager
Get-WindowsFeature |
Where-Object {$_.Installed -match “True”} |
ForEach-Object {
$_.Name | Write-Host
}
How about a nice one liner?
Get-WindowsFeature | ? {$_.Installed -match “True”} | Select -exp Name
If you can accept a totally static solution, this should work:
Write-Host $Arr[$i].Substring(2, $Arr[$i].Length-3)
If you're looking for a solution that looks specifically for those symbols and removes them, it would be a little different. Based on your question though, this should be just fine.

How to get Export-Csv to output same information as screen output?

Get-WmiObject -list | where-object {$_.name -match "win32"} | Select-Object
name,methods,properties
This displays the name, methods and properties of each Win32 class and I wanted to get this information into a CSV file.
The following however outputs doesn't output the same information.
Get-WmiObject -list | where-object {$_.name -match "win32"} | Select-Object
name,methods,properties | Export-CSV "c:\output.csv"
How can I do this?
(Updated my script as it had an error.)
You need to do some extra manual work and make sure you expand the names and join them by some delimiter:
$methods = #{n='Methods';e={ ($_.Methods | select -expand Name) -join ';'}}
$properties = #{n='Properties';e={ ($_.Properties | select -expand Name) -join ';'}}
Get-WmiObject -List |
Where-Object {$_.Name -like "Win32_*"} |
Select-Object Name,$methods,$properties |
Export-Csv .\win32.csv -NoTypeInformation
The problem here is that each WMI Object has properties that themselves are arrays and Output-CSV can't really handle that.
To fix this, you'd need to handle the arrays of arrays explicitly.
WHat specifically do you want to be output?