I modified one of my earlier scripts Link... Try something like this.
Function Get-DHCPEnabled {
param ([string]$path,[string]$computer,[switch]$verbose)
begin {
#create an empty array to hold our results.
$obj = @()
$computers = @()
if ($Verbose) {$VerbosePreference = "Continue"; $WarningPreference = "Continue"}
#validate our params... why js... why must you delay V2!
if ($path -and (Test-Path $path)) {
$computers = Get-Content $path
} elseif ($computer) {
$computers += $computer
} else {
Throw 'either -path <string> or -computer <string> must be supplied!'
}
}
process {
#Set ErrorAction to silent... we'll handle the error's ourselves.
$ErrorActionPreference = "SilentlyContinue"
foreach ($entry in $computers)
{
Write-Verbose "querying $entry ..."
$results = Get-Wmiobject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled=true" -ComputerName $entry
# If there was an error while attempting the gwmi call, there will be only one error.
# We check that error to help annotate why we were unsuccessful.
switch -regex ($Error[ 0 ].Exception)
{
"The RPC server is unavailable"
{
Write-warning "RPC Unavailable on $computer"
$obj += "" | Select @{e={$entry};n='Target'},@{e={"RPC_Unavalable"};n='caption'}
continue
}
#vista/2k8
"Access denied"
{
Write-warning "Access Denied on $computer"
$obj += "" | Select @{e={$entry};n='Target'},@{e={"Access_Denied"};n='caption'}
continue
}
#XP/Server 2k3
"Access is denied"
{
Write-warning "Access Denied on $computer"
$obj += "" | Select @{e={$entry};n='Target'},@{e={"Access_Denied"};n='caption'}
continue
}
# No error -> record our info!
$null
{
$obj += "" | Select @{e={$entry};n='Target'},@{e={$results.caption };n='caption'},@{e={$results.dhcpenabled };n='DHCP'}
}
}
$Error.clear()
}
}
end {
return $obj
}
}
Instead of writing to a file in your script output full objects, and then pipe those objects to out-file. like so...
Get-DHCPEnabled -path d:\pshellscripts\servers.txt | out-file d:\pshellscripts\list.txt -Encoding ASCII
or a slightly more interactive approach, perhaps something like....
Get-DHCPEnabled -path d:\pshellscripts\servers.txt | ? {$_.DHCP -eq "True"} | out-file d:\pshellscripts\list.txt -Encoding ASCII
As you can see this is where putting in the effort to keep your data in powershell and objectized realy starts to pay off. Also while I'm still a fan of the server.txt, I would recomend supporting both a file, and adhoc.
Get-DHCPEnabled -Computer Server20 -verbose
by building that support in early you enable the flexibility to do stuff like...
1..20 | %{ Get-DHCPEnabled -Computer Server$($_) -verbose }
or for the Vmware fan (ME!)
get-vm | % {Get-DHCPEnabled -Computer $_.name}
Hope that helps, if I failed to explain something please let me know!
~Glenn