A parameter cannot be found that matches parameter name 'PipelineVariable' - powershell

On two different machines joined to the same Windows 2008 R2 Active Directory domain, a Windows 7 workstation and a Windows 2008 R2 server, I am getting the following error when running a PowerShell script written by a Microsoft Field Engineer I downloaded from the Microsoft TechNet Gallery:
PS C:\Users\User1\Desktop> .\Find-PossibleMissingSPN.ps1
Get-ADObject : A parameter cannot be found that matches parameter name 'PipelineVariable'.
At C:\Users\User1\Desktop\Find-PossibleMissingSPN.ps1:37 char:114
+ Get-ADObject -LDAPFilter $filter -SearchBase $DN -SearchScope Subtree -Proper
ties $propertylist -PipelineVariable <<<< account | ForEach-Object {
+ CategoryInfo : InvalidArgument: (:) [Get-ADObject], ParameterBi
ndingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory
.Management.Commands.GetADObject
Various google searches have not yielded an answer. Does anyone know how to resolve this? Here's the actual code:
#.Synopsis
# To find possibly missing SPN registrations due to manual mistakes.
[CmdletBinding()]
Param
(
# start the search at this DN. Default is to search all of the domain.
[string]$DN = (Get-ADDomain).DistinguishedName
)
#
# define the SPN service classes to look for. Other types are mostly automated and should be OK.
#
$servicesclasses2check = #("host", "cifs", "nfs", "http", "mssql")
#
# get computers and users with a nonzero SPN within the given DN.
#
$filter = '(&(servicePrincipalname=*)(|(objectcategory=computer)(objectcategory=person)))'
$propertylist = #("servicePrincipalname", "samaccountname")
Get-ADObject -LDAPFilter $filter -SearchBase $DN -SearchScope Subtree -Properties $propertylist -PipelineVariable account | ForEach-Object {
#
# Create list of interesting SPNs for each account. Strong assumption for all code: SPN is syntactically correct.
#
$spnlist = $account.servicePrincipalName | Where-Object {
($serviceclass, $hostname, $service) = $_ -split '/'
($servicesclasses2check -contains $serviceclass) -and -not $service
}
#
# Look for cases where there is no pair of (host, host.domain) SPNs.
#
foreach ($spn in $spnlist)
{
($serviceclass, $hostname, $service) = $spn -split '/'
if ($service) { $service = "/$service" }
($fullname, $port) = $hostname -split ':'
if ($port) { $port = ":$port" }
($shortname, $domain) = $fullname -split '[.]'
#
# define the regexp matching the missing SPN and go look for it
#
if ($domain) {
$needsSPN = "${serviceclass}/${shortname}${port}${service}`$"
$needsSPNtxt = "${serviceclass}/${shortname}${port}${service}"
} else {
$needsSPN = "$serviceclass/${shortname}[.][a-zA-Z0-9-]+.*${port}${service}`$"
$needsSPNtxt = "$serviceclass/${shortname}.<domain>${port}${service}"
}
#
# search the array of SPNs to see if the _other_ SPN is there. If not, we have problem case.
#
if (-not ($spnlist -match $needsSPN))
{
[PSCustomobject] #{
samaccountname = $account.samaccountname
presentSPN = $spn
missingSPN = $needsSPNtxt
}
}
}
}

The -PipelineVariable common parameter is only available in PowerShell v4+. You need to upgrade to a later version for this to work.

Related

Check and Update multiple attributes of AD users

I am trying to do an update to Active Directory from a CSV.
I want to check each value to see if the AD and CSV values match.
If the AD value and CSV values don't match, then I want to update the AD value.
finally I want to create a log of the values changed, which would eventually be exported to a CSV report.
Now there is about 30 values I want to check.
I could do an if statement for each value, but that seems like the hard way to do it.
I am try to use a function, but I cant seem to get it working.
I am getting errors like:
set-ADUser : replace
At line:94 char:9
+ set-ADUser -identity $ADUser -replace #{$ADValue = $DIAccount ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (JDoe:ADUser) [Set-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser
set-ADUser : The specified directory service attribute or value does not exist
Parameter name: Surname
At line:94 char:9
+ set-ADUser -identity $ADUser -replace #{$ADValue = $DIAccount ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (JDoe:ADUser) [Set-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser
Any suggestions would be welcome
Code I am using:
Function AD-Check ($ADValue, $ADUser, $ADAccount, $UpdateAccount)
{
If ($ADAccount -ne $UpdateAccount)
{
set-ADUser -identity $ADUser -replace #{$ADValue = $UpdateAccount}
$Change = "Updated"
}
Else
{
$Change = "No Change"
}
Return $Change
}
$Import = get-content C:\temp\ADUpdates.csv
Foreach ($user in $Import)
{
$Account = get-aduser $User.Samaccountname -Properties *
#First Name Check
$Test = AD-Check "GivenName" $Account.samaccountname $Account.givenname $user.givenname
$ChangeGivenName = $Test
#Initials Check
$Test = AD-Check "Initials" $Account.samaccountname $Account.Initials $user.Initials
$ChangeInitials = $Test
#Last Name Check
$Test = AD-Check "Surname" $Account.samaccountname $Account.SurnameSurname $user.Surname
$ChangeSurname = $Test
}
Reply to Theo, cant seem to add this any other way...
Thanks Theo, it seems to make sense, but getting an error.
Select-Object : Cannot convert System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection to one of the following types {System.String,
System.Management.Automation.ScriptBlock}.
changed the following to get all properties for testing and it works.
$Account = Get-ADUser -Filter "SamAccountName -eq '$sam'" -ErrorAction SilentlyContinue -Properties $propsToCheck
Left the following and it kicks the error
$oldProperties = $Account | Select-Object $propsToCheck
Using the following just for testing:
$propertiesMap = [ordered]#{
SamAccountName = 'sAMAccountName'
mail = 'mail'
GivenName = 'givenName'
Initials = 'initials'
Surname = 'sn'
Office = 'physicalDeliveryOfficeName'
MobilePhone = 'mobile'
DistinguishedName = 'DistinguishedName'
}
Starting of with a WARNING:
Replacing user attributes is not something to be taken lightly and you
need to check any code that does that on a set of testusers first.
Keep the -WhatIf switch to the Set-ADUser cmdlet so you
can first run this without causing any problems to the AD.
Only once you are satisfied all goes according to plan, remove the -WhatIf switch.
Please carefully read all inline comments in the code.
In your code you use an input CSV file, apparently with properties and values to be checked/updated, but instead of using Import-Csv, you do a Get-Content on it, so you'll end up with just lines of text, not an array of parsed properties and values..
Next, as Mathias already commented, you need to use the LDAP attribute names when using either the -Add, -Remove, -Replace, or -Clear parameters of the Set-ADUser cmdlet.
To do what you intend to do, I would first create a hashtable to map the PowerShell attribute names to their LDAP equivalents.
To see which property name maps to what LDAP name, you can use the table here
# create a Hashtable to map the properties you want checked/updated
# the Keys are the PowerShell property names as they should appear in the CSV
# the Values are the LDAP AD attribute names in correct casing.
$propertiesMap = [ordered]#{
SamAccountName = 'sAMAccountName'
GivenName = 'givenName'
Initials = 'initials'
Surname = 'sn'
Office = 'physicalDeliveryOfficeName'
Organization = 'o'
MobilePhone = 'mobile'
# etcetera
}
# for convenience, store the properties in a string array
$propsToCheck = $propertiesMap.Keys | ForEach-Object { $_.ToString() }
# import your CSV file that has all the properties you need checked/updated
$Import = Import-Csv -Path 'C:\temp\ADUpdates.csv'
# loop through all items in the CSV and collect the outputted old and new values in variable $result
$result = foreach ($user in $Import) {
$sam = $user.SamAccountName
# try and find the user by its SamAccountName and retrieve the properties you really want (not ALL)
$Account = Get-ADUser -Filter "SamAccountName -eq '$sam'" -ErrorAction SilentlyContinue -Properties $propsToCheck
if (!$Account) {
Write-Warning "A user with SamAccountName '$sam' does not exist"
continue # skip this one and proceed with the next user from the CSV
}
# keep an object with the current account properties for later logging
$oldProperties = $Account | Select-Object $propsToCheck
# test all the properties and create a Hashtable for the ones that need changing
$replaceHash = #{}
foreach ($prop in $propsToCheck) {
if ($Account.$prop -ne $user.$prop) {
$ldapAttribute = $propertiesMap[$prop] # get the LDAP name from the $propertiesMap Hash
# If any of the properties have a null or empty value Set-ADUser will return an error.
if (![string]::IsNullOrWhiteSpace($($user.$prop))) {
$replaceHash[$ldapAttribute] = $user.$prop
}
else {
Write-Warning "Cannot use '-Replace' with empty value for property '$prop'"
}
}
}
if ($replaceHash.Count -eq 0) {
Write-Host "User '$sam' does not need updating"
continue # skip this one and proceed with the next user from the CSV
}
# try and do the replacements
try {
##########################################################################################################
# for safety, I have added a `-WhatIf` switch, so this wll only show what would happen if the cmdlet runs.
# No real action is performed when using '-WhatIf'
# Obviously, there won't be any difference between the 'OLD_' and 'NEW_' values then
##########################################################################################################
$Account | Set-ADUser -Replace $replaceHash -WhatIf
# refresh the account data
$Account = Get-ADUser -Identity $Account.DistinguishedName -Properties $propsToCheck
$newProperties = $Account | Select-Object $propsToCheck
# create a Hashtable with the old and new values for log output
$changes = [ordered]#{}
foreach ($prop in $propsToCheck) {
$changes["OLD_$property"] = $oldProperties.$prop
$changes["NEW_$property"] = $newProperties.$prop
}
# output this as object to be collected in variable $result
[PsCustomObject]$changes
}
catch {
Write-Warning "Error changing properties on user '$sam':`r`n$($_.Exception.Message)"
}
}
# save the result as CSV file so you can open with Excel
$result | Export-Csv -Path 'C:\temp\ADUpdates_Result.csv' -UseCulture -NoTypeInformation

Get-ADGroupMember processing for non domain members

We have a trusted domain that we administer and users are given acceess to a file server on our domain through groups on the trusted domain added to the local domain group which controls permissions e.g.
For the path "\server\folder\folder" the permissions might look like
MyDomain\FolderXReadWrite
Then within that group a group from the trusted domain would be included
TrustedDomain\FolderXReadWrite
I'd like to write a script to "reverse engineer" this so that I can derive both the local and trusted domain groups that have access from a given folder path and list them - I've got the following:
$path = '\\server\path\path'
$Permissions = (Get-Item -Path $path -ErrorAction Stop | Get-Acl -ErrorAction Stop).Access | Where-Object { $_.IdentityReference -like "MyDomain\*" } | ForEach-Object {
$TrustedDomGroup = Get-ADGroupMember ($_.IdentityReference.Value -split '\\')[1] -Verbose | Where-Object { ($_.DistinguishedName -split 'DC=', 2)[-1] -like "*TrustedDomain*" -and ($_.objectClass -eq 'group') }
If ($TrustedDomGroup) {
[pscustomobject]#{Name=("TrustedDomain\" + $TrustedDomGroup.SamAccountName);Rights=("Member of " + $_.IdentityReference);Domain='PHS'}
}
[pscustomobject]#{Name=$_.IdentityReference;Rights=$_.FileSystemRights;Domain='NSS'}
}
$Permissions | Sort-Object Name -Unique
This produces the output I require, however, the domain group in the above example has LOTS of users therefore processing "Get-ADGroupMember" takes a long time. Does anyone have suggestions for a faster method?
you can try to retrieve all group members with this command:
(Get-ADGroup $ADGroup -Properties members).members
I don't know if it's faster in your environment then Get-AdGroupMember.
A measurement via Measure-Command may give you more information:
Measure-Command, Microsoft Docs
Ok, so the best method to improve the lookup speed seems to be using LDAP so I put together a small function to get Foreign Security Principal group names from a local AD group:
Function List-FSPGroupMembers {
# Use LDAP search to find and resolve Foreign Security Principals from an AD group - faster than native cmdlet
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=1)][string]$GroupName="",
[Parameter(Mandatory=$true,Position=2)][string]$Domain
)
[regex]$SIDmatch = "S-\d-(?:\d+-){1,14}\d+"
Function fGetADGroupObjectFromName([System.String]$sGroupName,[System.String]$sLDAPSearchRoot) {
$oADRoot = New-Object System.DirectoryServices.DirectoryEntry($sLDAPSearchRoot)
$sSearchStr ="(&(objectCategory=group)(name="+$sGroupName+"))"
$oSearch=New-Object directoryservices.DirectorySearcher($oADRoot,$sSearchStr)
$oFindResult=$oSearch.FindAll()
If($oFindResult.Count -eq 1) {
Return($oFindResult)
}
Else{
Return($false)
}
}
$sSearchRoot="LDAP://" + $Domain + ":3268"
If($oSearchResult=fGetADGroupObjectFromName $groupname $sSearchRoot) {
$oGroup=New-Object System.DirectoryServices.DirectoryEntry($oSearchResult.Path)
$oGroup.Member | Where-Object {($_.ToString()) -match $SIDmatch } | ForEach-Object {
$SID = (Select-String -Pattern $SIDmatch -InputObject $_.ToString()).Matches.Value
Try {
(New-Object System.Security.Principal.SecurityIdentifier($SID)).Translate([System.Security.Principal.NTAccount]).Value
}
Catch {
$_
}
}
}
Else {
Write-Warning ("Group "+$groupname+" not found at "+$domain)
}
}

Remote registry key extractor PowerShell script

I am trying to create a PowerShell script that remotely checks each machine on the domain for a registry key entry, then outputs that key value along with the machine name to a .csv file.
So far the script outputs all the machines on the domain to a .csv file but puts its local registry key value not the value of the remote machine.
Any help would be greatly appreciated, here is what I have so far.
Import-Module ActiveDirectory
$SRVS = Get-ADComputer -Filter * -SearchBase 'DC=mydomain,DC=local' |
select dnshostname
foreach ($SRV in $SRVS) {
$REG = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $SRV.name)
$REGKEY = $REG.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\QualityCompat")
$MELT = $REGKEY.GetValue('cadca5fe-87d3-4b96-b7fb-a231484277cc')
"$($SRV);$($MELT)" | Out-File C:\Users\user1\Desktop\regkeys.CSV -Append
}
The statement
$SRVS = Get-ADComputer ... | select dnshostname
gives you a list of custom objects with only one property: dnshostname. But in your loop you're trying to use a property name, which those custom objects don't have. Hence the statement
[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $SRV.name)
effectively becomes
[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $null)
meaning you're opening the local registry, not the registry on a remote host.
Change $SRV.name to $SRV.dnshostname and the problem will disappear.
Once it's been instanced the RegistryKey class does not expose that it's a remote key. That means you have to record the computer name yourself. There's also no standard format for a remote registry value.
If I had a PowerShell v5+, I would use something like this:
Import-Module ActiveDirectory
# No need for the Select-Object here since we're using $SRV.Name later
$SRVS = Get-ADComputer -Filter * -SearchBase 'DC=mydomain,DC=local'
# Create an arraylist to save our records
$Report = New-Object System.Collections.ArrayList
# This try finally is to ensure we can always write out what we've done so far
try {
foreach ($SRV in $SRVS) {
# Test if the remote computer is online
$IsOnline = Test-Connection -ComputerName $SRV.Name -Count 1 -Quiet;
if ($IsOnline) {
# If system is Online
$REG = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $SRV.name)
$REGKEY = $REG.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\QualityCompat")
$MELT = $REGKEY.GetValue('cadca5fe-87d3-4b96-b7fb-a231484277cc')
# Create a PSObject record for convenience
$Record = [PSCustomObject]#{
ComputerName = $SRV;
Key = $REGKEY.Name;
Value = $MELT;
}
}
else {
# If system is Offline
# Create a PSObject record for convenience
$Record = [PSCustomObject]#{
ComputerName = $SRV;
Key = '';
Value = '';
}
}
# Add our record to the report
$Report.Add($Record);
}
}
finally {
# Always write out what we have whether or not we hit an error in the middle
$Report | Export-Csv -Path "C:\Users\user1\Desktop\regkeys.csv" -NoTypeInformation
}
That may work on PowerShell v3+, but I don't have it around anymore to test.
Any reason you are trying to printout the actual regkey vs just checking for it's existence?
It either exists or it does not. Say using something like...
Clear-Host
Import-Module ActiveDirectory
$SRVS = (Get-ADComputer -Filter * -SearchBase (Get-ADDomainController).DefaultPartition)
$MeltHive = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\QualityCompat'
$MeltHiveKey = 'cadca5fe-87d3-4b96-b7fb-a231484277cc'
ForEach($Srv in $SRVS)
{
Invoke-Command -ComputerName $Srv.Name -ScriptBlock {
If (Get-ItemProperty -Path $Using:MeltHive -Name $MeltHiveKey -ErrorAction SilentlyContinue)
{"On Host $env:COMPUTERNAME MELT registry information exists"}
Else {Write-Warning -Message "On host $env:COMPUTERNAME MELT registry information does not exist"}
}
}
ForEach($Srv in $SRVS)
{
Invoke-Command -ComputerName $Srv.Name -ScriptBlock {
If ((Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion) -match 'QualityCompat')
{"On Host $env:COMPUTERNAME MELT registry information exists"}
Else {Write-Warning -Message "On host $env:COMPUTERNAME MELT registry information does not exist"}
}
}
Results of both the above is:
WARNING: On host DC01 MELT registry information does not exist
WARNING: On host EX01 MELT registry information does not exist
WARNING: On host SQL01 MELT registry information does not exist
On Host IIS01 MELT registry information exists

Remove Symantec Endpoint Protection in an Enterprise Environment

I have many servers I need to remove Symantec Endpoint Protection from. I contacted Symantec and received the code below:
(Get-WmiObject -Class Win32_Product -Filter "Name='Symantec Endpoint Protection'" -ComputerName xxxxxx).Uninstall()
I have used it and it worked on 10 servers no problem at all. I tried it again today and am getting the error:
You cannot call a method on a null-valued expression.
At line:1 char:1
+ (Get-WmiObject -Class Win32_Product -Filter "Name='Symantec Endpoint Protection' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
Nothing has changed from when I started and am trying to figure out what the above error means. Also if I can get this to work does anyone see a way to add many servers to a foreach command or something.
Two things from my side:
1) you should not use win32_product cause it is broken to a certain level.
It is very slow alsso because it scans the entire thing.
2) In your case, "Name='Symantec Endpoint Protection'" reports Null for you which means that the value is not there. Please check the proper name.
For better performance and as part of enhancement , you should use the registry to fetch the details.
Function Get-RemoteSoftware{
<#
.SYNOPSIS
Displays all software listed in the registry on a given computer.
.DESCRIPTION
Uses the SOFTWARE registry keys (both 32 and 64bit) to list the name, version, vendor, and uninstall string for each software entry on a given computer.
.EXAMPLE
C:\PS> Get-RemoteSoftware -ComputerName SERVER1
This shows the software installed on SERVER1.
#>
param (
[Parameter(mandatory=$true,ValueFromPipelineByPropertyName=$true)][string[]]
# Specifies the computer name to connect to
$ComputerName
)
Process {
foreach ($Computer in $ComputerName)
{
#Open Remote Base
$reg=[microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$Computer)
#Check if it's got 64bit regkeys
$keyRootSoftware = $reg.OpenSubKey("SOFTWARE")
[bool]$is64 = ($keyRootSoftware.GetSubKeyNames() | ? {$_ -eq 'WOW6432Node'} | Measure-Object).Count
$keyRootSoftware.Close()
#Get all of they keys into a list
$softwareKeys = #()
if ($is64){
$pathUninstall64 = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
$keyUninstall64 = $reg.OpenSubKey($pathUninstall64)
$keyUninstall64.GetSubKeyNames() | % {
$softwareKeys += $pathUninstall64 + "\\" + $_
}
$keyUninstall64.Close()
}
$pathUninstall32 = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
$keyUninstall32 = $reg.OpenSubKey($pathUninstall32)
$keyUninstall32.GetSubKeyNames() | % {
$softwareKeys += $pathUninstall32 + "\\" + $_
}
$keyUninstall32.Close()
#Get information from all the keys
$softwareKeys | % {
$subkey=$reg.OpenSubKey($_)
if ($subkey.GetValue("DisplayName")){
$installDate = $null
if ($subkey.GetValue("InstallDate") -match "/"){
$installDate = Get-Date $subkey.GetValue("InstallDate")
}
elseif ($subkey.GetValue("InstallDate").length -eq 8){
$installDate = Get-Date $subkey.GetValue("InstallDate").Insert(6,".").Insert(4,".")
}
New-Object PSObject -Property #{
ComputerName = $Computer
Name = $subkey.GetValue("DisplayName")
Version = $subKey.GetValue("DisplayVersion")
Vendor = $subkey.GetValue("Publisher")
UninstallString = $subkey.GetValue("UninstallString")
InstallDate = $installDate
}
}
$subkey.Close()
}
$reg.Close()
}
}
}
Note: Use the function or the query inside the function to get the result.
Hope it helps.

Resolve-DNSName for Windows 2008

I have a script working for Windows 2012 (PowerShell v4) but it has to work also for Windows 2008 (PowerShell v2), what is the equivalent of the cmdlet "Resolve-DNSName" for Windows 2008?
Resolve-DnsName -Name client01 -Server server01
I know it exists the same for nslookup and this is what I would like as a cmdlet (one-liner, with no input required from my part)
nslookup
server server01
client01
The following works for DNS resolution but is missing the -server parameter :
[Net.DNS]::GetHostEntry("MachineName")
Thanks
Unfortunately there isn't a way to do this natively in powershell prior to Version 4 in Windows 8.1 or Server 2012. There are .NET methods however:
https://stackoverflow.com/a/8227917/4292988
The simplest solution in powershell is to call nslookup, and cleanup the output
&nslookup.exe client01 server01
I removed select-string from the original sample, it left less to work with
The function you posted following mine doesnt work very well, and will never work in PowershellV2, [PSCustomObject] wasn't supported until v3. Furthermore if you send a dns query that would normally return a single address, it returns nothing. For queries with aliases, it returns the aliases where the ipaddress should be. Test Resolve-DnsName2008 -name www.stackoverflow.com -server 8.8.8.8.
The Following is a function that should do what your asking, at least for ipv4addresses:
function Resolve-DnsName2008
{
Param
(
[Parameter(Mandatory=$true)]
[string]$Name,
[string]$Server = '127.0.0.1'
)
Try
{
$nslookup = &nslookup.exe $Name $Server
$regexipv4 = "^(?:(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)$"
$name = #($nslookup | Where-Object { ( $_ -match "^(?:Name:*)") }).replace('Name:','').trim()
$deladdresstext = $nslookup -replace "^(?:^Address:|^Addresses:)",""
$Addresses = $deladdresstext.trim() | Where-Object { ( $_ -match "$regexipv4" ) }
$total = $Addresses.count
$AddressList = #()
for($i=1;$i -lt $total;$i++)
{
$AddressList += $Addresses[$i].trim()
}
$AddressList | %{
new-object -typename psobject -Property #{
Name = $name
IPAddress = $_
}
}
}
catch
{ }
}
I use this code to input FQDNs one per line and output respective IPs.
$Server = Get-Content servers.txt
$OutArray = #()
$output = foreach ($Server in $Server) {
$IP = [System.Net.Dns]::GetHostAddresses($Server)
$OutArray += $Server + " " + $IP.IPAddressToString
}
$OutArray | Out-File IPs.txt
The problem is that if I use :
&nslookup.exe client01 server01 | select-string "Name", "Addresses"
It will only display the first record, in my case I had 5 records found and only one displayed.
The solution I found works very well :
function Resolve-DNSName2008
{
Param
(
[string]$Name,
[string]$Server
)
$nslookup = &nslookup.exe $Name $Server
$name = [string]($nslookup | Select-String "Name")
$nameClean = ([regex]::match($name,'(?<=:)(.*\n?)').value).Trim()
$addresses = (([regex]::match($nslookup,'(?<=Addresses:)(.*\n?)').value).Trim()).Split(' ')
$addressesClean = $addresses.Split('',[System.StringSplitOptions]::RemoveEmptyEntries) | Sort-Object
$addressesClean | %{
[PSCustomObject]#{
Name = $nameClean
IPAddress = $_
}
}
}
Usage:
Resolve-DNSName2008 -Name server.domain.com -Server 10.0.0.0
Output:
Name IPAddress
---- ---------
server.domain.com 10.0.0.1
server.domain.com 10.0.0.2
server.domain.com 10.0.0.3
server.domain.com 10.0.0.4
server.domain.com 10.0.0.5