So, I have a script that does a write-host to the console (see script below). I’ve tried everything to get this thing to write to file…
I’ve tried just calling the script and passing the to the out-file parameter like this:
C:> .myscript.ps1 | out-file results.txt
I’ve tried:
C:> .myscript.ps1 > results.txt
I’ve tried re-writing the script to use write-output instead of write-host and it works for the first two write-host statements (hostname and template) but not the ‘device name’ statement which is in the for loop.
Hoping someone can help me get this info into a file. It needs to be something that is nor version specific as we’re stuck using a very old version of powershell.
Sorry, it’s not my language of expertise so the code below might look a bit shabby,It works though, but only to the console.
#Conecting and gathering information
$objDomain = new-object system.directoryServices.directoryEntry
$strTopDomain = $objDomain.distinguishedName
$strTopLDAP = “LDAP://OU=Topology,OU=APC,OU=Applications,$strTopDomain”
$objTopOU = new-object system.directoryServices.directoryEntry(“$strTopLDAP”)
$strTopOU = $objTopOU.distinguishedName
$topFilter = “(&(sita-Vps-computerLink=)(sita-Vps-iwsTemplateLink=))”
$topObjSearcher = New-Object System.DirectoryServices.DirectorySearcher($topFilter)
$topObjSearcher.searchRoot = $objTopOU
$topObjSearcher.searchScope = “subtree”
$topObjSearcher.sizelimit = 1000
$properties=@(‘name’,‘sita-Vps-iwsTemplateLink’)
$topObjSearcher.PropertiesToLoad.AddRange($properties)
$hash = @{}
$objTopList = $topObjSearcher.findAll() |
foreach-object{
$hash.Add($.Properties.Item(“name”)[0], $.Properties.Item(“sita-Vps-iwsTemplateLink”)[0].toString().split(‘,=’)[1])}
$objIwsDomain = new-object system.directoryServices.directoryEntry
$strIwsDomain = $objIwsDomain.distinguishedName
$iwsFilter = “(sita-Vps-deviceTemplate=*)”
$strIwsLDAP = “LDAP://OU=IwsTemplates,OU=APC,OU=Applications,$strIwsDomain”
$objIwsOU = new-object system.directoryServices.directoryEntry(“$strIwsLDAP”)
$strIwsOU = $objIwsOU.distinguishedName
$iwsObjSearcher = New-Object System.DirectoryServices.DirectorySearcher($iwsFilter)
$iwsObjSearcher.searchRoot = $objIwsOU
$iwsObjSearcher.searchScope = “subtree”
$iwsObjSearcher.sizelimit = 1000
$iwsProperties=@(‘distinguishedName’,‘sita-vps-deviceTemplate’)
$iwsObjSearcher.PropertiesToLoad.AddRange($iwsProperties)
#Looping through gathered information and displaying
foreach($i in $hash.keys){
write-host “Hostname: $i” | Out-File -filepath "c:" -append -encoding utf8;
Write-host “Template:” “$($hash.$i)” | Out-File -filepath "c:" -append -encoding utf8;
$objIwsList = $iwsObjSearcher.findAll() |
foreach-object{
$tmp_name = ($.Properties.Item(“distinguishedName”)[0].split(‘,=’)[3]);
$tmp_device = ($.Properties.Item(“sita-Vps-deviceTemplate”)[0].toString().split(‘,=’)[1])|
where-object{$tmp_name -eq $hash.$i
if($tmp_device -ne $null){write-host “Device:” $tmp_device | Out-File -filepath "c:" -append -encoding utf8}
}
}
}