PowerShell AD script not working - powershell

For some reason everything works except the homeDirectory. For that everything is blank..The AD actually has values for these fields but this script isn't displaying anything for that attribute. Any ideas?
$objSearch = New-Object System.DirectoryServices.DirectorySearcher
$objSearch.PageSize = 15000
$objSearch.Filter = $ObjFilter
$objSearch.SearchRoot = "LDAP://$dn"
$AllObj = $objSearch.FindAll()
foreach ($Obj in $AllObj)
{ $objItemS = $Obj.Properties
$Ssamaccountname = $objItemS.samaccountname
$SsamaccountnameGN = $objItemS.givenname
$SsamaccountnameSN = $objItemS.sn
$SsamaccountnameEN = $objItemS.mail
$SsamaccountnameLS = $objItemS.homeDirectory
"$Ssamaccountname`t$SsamaccountnameGN`t$SsamaccountnameSN`t$SsamaccountnameEN`t$SsamaccountnameLS" | Out-File $UserInfoFile -encoding ASCII -append
} # End of foreach
} # End of ForEach-Object

If you are not attached to using the .NET I really like Quest Active Directory cmdlets
Your command would then be:
get-qadUser <UserName or another unique attribute> | Format-List <Attributes> | Out-File MyTextFile.txt
To get a list of possible attributes, you can:
get-qaduser UserName -includeAllAttribute | fl * | Out-File C:\AllAttributes.txt

Can you retry adding this line before the FindAll:
$objSearch.PropertiesToLoad.Add("homeDirectory");
Generaly speaking it's better to add to the search each attribute you want to retreive.

Related

Exporting PowerShell Results In To CSV for Each User In The Domain That Last Changed Their Password

I have a Powershell script that queries for the pwdLastSet attribute for every user in
the Active Directory domain. Essentially, the script determines when each user in the domain last changed their password. However, when I try and output the result using scriptname.ps1 | Export-Csv "filename.csv" it creates the file, however, I'm not getting the results I see in the console. I'm getting the following:
When I run the script without Export-Csv the results I desire display correctly.
This is the Powershell script:
Trap {"Error: $_"; Break;}
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("pwdLastSet") > $Null
$Searcher.PropertiesToLoad.Add("userAccountControl") > $Null
$Searcher.SearchRoot = "LDAP://" + $Domain.distinguishedName
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
$DN = $Result.Properties.Item("distinguishedName")
$PLS = $Result.Properties.Item("pwdLastSet")
$UAC = $Result.Properties.Item("userAccountControl")
# Retrieve user password settings to check if password can expire.
$blnPwdExpires = -not (($UAC.Item(0) -band 64) -or ($UAC.Item(0) -band 65536))
If ($PLS.Count -eq 0)
{
$Date = [DateTime]0
}
Else
{
# Interpret 64-bit integer as a date.
$Date = [DateTime]$PLS.Item(0)
}
If ($Date -eq 0)
{
# 0 really means never.
$PwdLastSet = "<Never>"
}
Else
{
# Convert from .NET ticks to Active Directory Integer8 ticks.
# Also, convert from UTC to local time.
$PwdLastSet = $Date.AddYears(1600).ToLocalTime()
}
"$DN;$blnPwdExpires;$PwdLastSet"
}
There are two possible issues on your code, the first one, Export-Csv is expecting an object or object[] as input and will convert it to CSV format, you're already passing a formatted semi-colon delimited string[].
In this case you should use | Out-File path\to\csv.csv instead of Export-Csv.
Do not format objects before sending them to the Export-CSV cmdlet. If Export-CSV receives formatted objects the CSV file contains the format properties rather than the object properties.
An example of what you're passing to the cmdlet and what it actually expects:
PS \> 0..5 | ForEach-Object{ 'asd;asd;asd' } | ConvertTo-Csv
#TYPE System.String
"Length"
"12"
"12"
"12"
"12"
"12"
"12"
PS \> 0..5 | ForEach-Object{ [pscustomobject]#{col1='asd';col2='asd';col3='asd'} } | ConvertTo-Csv -Delimiter ';'
#TYPE System.Management.Automation.PSCustomObject
"col1";"col2";"col3"
"asd";"asd";"asd"
"asd";"asd";"asd"
"asd";"asd";"asd"
"asd";"asd";"asd"
"asd";"asd";"asd"
"asd";"asd";"asd"
The alternative to this, and cleaner approach in my opinion, would be to cast a [pscustomobject]on each iteration of your loop and then pass the resulting array to Export-Csv (code below).
The other possible issue, assuming you're choosing the path of using [pscustomobject], could be that $Result.Properties.Item(...) will yield an object of the type System.DirectoryServices.ResultPropertyValueCollection and you would need to convert it to [string] before passing the results to Export-Csv (also code below).
# Save the resulting pscustomobject array to the $output variable
$output = ForEach ($Result In $Results)
{
...
...
...
# All code should be as is up until:
# "$DN;$blnPwdExpires;$PwdLastSet" => Remove this line
[pscustomobject]#{
DistinguishedName = [string]$DN
blnPwdExpires = [string]$blnPwdExpires
pwdLastSet = [string]$PwdLastSet
}
}
# Then pipe the result to Export-Csv
$output | Export-Csv path\to\csv.csv -NoTypeInformation -Delimiter ';'

For each thing in one CSV check for multiple types of matches in another CSV

Sorry if the description is unclear, but I couldn't think of how else to word it.
I have two CSV files:
LocalAdmins.csv -- ColumnA = PC name; ColumnB = username in local admin group
Exempt.csv -- ColumnA = PC name; ColumnB = username allowed to be a local admin
What I'm trying to do is loop through LocalAdmins.csv, and for each one check to see if the PC name shows up in Exempt.csv (or matches any defined naming patterns in that file), and if a match is found, check to see if the local admin username for that PC in LocalAdmins.csv shows up in the list of AllowedUsers for that PC in Exempt.csv.
If the username is NOT in the AllowedUsers list, or if the PC name is not in Exempt.csv, then output the entry from LocalAdmins.csv. Here is what I have so far:
$admins = Import-Csv .\LocalAdmins.csv
$exempt = Import-Csv .\Exempt.csv
$violations = ".\Violations.csv"
foreach ($admin in $admins) {
foreach ($item in $exempt) {
if ($admin.PC -like $item.PC) {
if ($admin.Name -notin ($item.AllowedUsers -split ",")) {
$admin | Export-Csv $violations -Append -NoTypeInformation
}
}
else {
$admin | Export-Csv $violations -Append -NoTypeInformation
}
}
}
The problem is the nested foreach loop generates duplicates, meaning if there are 3 lines in Exempt.csv then a single entry in LocalAdmins.csv will have 3 duplicate outputs (one for each line in Exempt.csv). So the output looks like this:
When it should look like this:
I'm guessing the problem is somewhere in the structure of the loops, but I just need some help figuring out what to tweak. Any input is greatly appreciated!
Not optimized (unique sort by any property should work):
$admins = Import-Csv .\LocalAdmins.csv
$exempt = Import-Csv .\Exempt.csv
$violations = ".\Violations.csv"
$(
foreach ($admin in $admins) {
foreach ($item in $exempt) {
if ($admin.PC -like $item.PC) {
if ($admin.Name -notin ($item.AllowedUsers -split ",")) {
$admin
}
}
else {
$admin
}
}
}
) | Sort-Object -Property PC, Name -Unique |
Export-Csv $violations -Append -NoTypeInformation
With better restrictions of the forEach, there shouldn't be duplicates
and no need to Sort -unique.
Getting input from here-strings
## Q:\Test\2019\02\05\SO_54523868.ps1
$admins = #'
PC,NAME
XYZlaptop,user6
workstationXYZ,user7
computerABC,user8
ABClaptop,user1
'# | ConvertFrom-Csv # .\LocalAdmins.csv
$exempt = #'
PC,AllowedUsers
*laptop,"user1,user2"
computerXYZ,"user3,user4"
workstation*,"user5"
'# | ConvertFrom-Csv # .\Exempt.csv
$violationsFile = ".\Violations.csv"
$violations = foreach ($admin in $admins) {
$violation = $True
foreach ($item in ($exempt|Where-Object {$admin.PC -like $_.PC})){
if ($admin.NAME -in ($item.AllowedUsers -split ',')){
$violation = $False
}
}
if ($violation){$admin}
}
$violations
$violations | Export-Csv $violationsFile -NotypeInformation
## with Doug Finke's ImportExcel module installed, you can directly get the excel file:
#$violations | Export-Excel .\Violatons.xlsx -AutoSize -Show

In Powershell, how do I print out only the data from today(or a specific date range)?

I have a shared Outlook folder, where I need to extract 6-digit numbers from Email subject lines. So I use the following script :
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $outlook.GetNameSpace("MAPI")
$SharedMB = $NameSpace.Folders | Where{$_.Name -match "FDA UFMS User Provision"}
$OtherFldr = $SharedMB.Folders | Where{$_.Name -match "Inbox"}
[datetime]$StartDate = ([datetime]::now.ToShortDateString())
$TodaysMail = #()
for($i = ($OtherFldr.Items.count - 1);$i -ge 0;$i--){
$Current = $OtherFldr.Items.item($i)
if($Current.senton -lt (get-date $StartDate)){break}
else { $OtherFldr.Items | %{ $RESULT=[Regex]::Match ($_.TaskSubject, "Request\s\d{6}"); if ($RESULT.Success){$RESULT.
Value}} | %{$Result=[Regex]::Match($_, "\d{6}"); if ($RESULT.Success){$RESULT.Value}} | Out-File C:\Temp\powerfish4.txt
-Append }
$TodaysMail += $Current
}
But this throws up a strange error to me :
The funny thing, is that if I simply dump all the numbers into a text file, it does not have this permission error. That is, I can run this script just fine :
$OtherFldr.Items | %{ $RESULT=[Regex]::Match($_.TaskSubject, "Request\s\d{6}"); if ($RESULT.Success)
{$RESULT.Value}} | %{$Result=[Regex]::Match($_, "\d{6}"); if($RESULT.Success){$RESULT.Value}} | Out-File C:\Temp\powerfish2.txt -Append
I'm currently trying to play with Outlook's offline-mode.
any tips appreciated , thanks
This is just an assumption but maybe trying to copy the entire item requires Outlook to be online.(Maybe Outlook is not caching the entire item)
$Current = $OtherFldr.Items.item($i)
I don't have a list of properties that Outlook holds as a cache but maybe just dealing with tasksubject and senton might be available in cache.
Also modified the for loop to make it more simple.
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $outlook.GetNameSpace("MAPI")
$SharedMB = $NameSpace.Folders | Where{$_.Name -match "FDA UFMS User Provision"}
$OtherFldr = $SharedMB.Folders | Where{$_.Name -match "Inbox"}
[datetime]$StartDate = ([datetime]::now.ToShortDateString())
ForEach($Item in $OtherFldr.Items){
if($Item.senton -lt (get-date $StartDate)){break}
if($Item.TaskSubject -Match "Request\s\d{6}")
{
$Result=[Regex]::Match($Item.TaskSubject, "\d{6}");
if($RESULT.Success){
$RESULT.Value | Out-File C:\Temp\powerfish4.txt -Append
}
}
}

Check for DNS record using PowerShell 2.0

What could be the best way to resolve a computer name apart from using:
[System.Net.DNS]::GetHostByName('MachineName').HostName
I dont want to import any specific DNS Modules.
You can try the GetHostEntry method:
[Net.DNS]::GetHostEntry("MachineName")
Another way would be to ping it using Test-Connection cmdlet, see this tip
I was in a case where I had to query a specific DNS server, which is not possible directly with .net / powershell. So I ended up with using the good old nslookup :
$client="10.110.10.10"
$ns="10.20.1.10"
(nslookup $client $ns |sls name).toString().split(":")[1].trim()
The following 2 ways to resolve IP's to DNS addresses are the only ones.
It's how you use it that counts.
[Net.DNS]::GetHostEntry("MachineName")
[System.Net.DNS]::GetHostByName('MachineName').HostName
Like I said, It's how you use them.
I have written a script for doing just this.
It takes a list of IP addresses and resolves there DNS.
Later in the script it converts the output to an excel sheet, showing you the results.
Based upon filters you can set the layout.
Now I know not all IP's will be resolved with these methods, that's why I included a function in my script that filters out unresolved IP's and places them to the bottom of the excel sheet.
(Giving every IP a direct link to who.is/whois/ipadress
Here's the script, íf you are interested.
#Get current date
$Date = date -format yyyy-MM-dd
$Company = "Company"
$Company2 = "Company2"
########################
#Define all Paths.
$Path = "C:\inetpub\wwwroot\BlockedIP" #This is where your file's will be saved.
md "$Path\HTML\$Date" -Force |Out-Null
$path2 = "$Path\HTML\$Date"
$PathWeb = "/ResolvedIp/HTML/$Date"
########################
#Define File's used or created in this script.
$File = "$Path\IP-$Date.txt"
$FileHtml = "$Path2\IP-$Date.htm"
$FileXML = "$Path\IP-$Date.xlsx"
$FileHTMLWeb = "$PathWeb\IP-$date.htm"
######################################
#Define error actions.
$erroractionpreference = "SilentlyContinue"
###########################################
#Since the script used COM objects it will need the following 2 folders:
#(32Bit)
MD "C:\Windows\System32\config\systemprofile\Dektop" -force
MD "C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Windows\Temporary Internet" -force
#(64Bit)
MD "C:\Windows\SysWOW64\config\systemprofile\Desktop" -force
MD "C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft\Windows\Temporary Internet" -force
#Once successfull the script will run without a problem if scheduled.
cls
(gc $File) | ? {$_.trim() -ne "" } | set-content $File
$IPCount = (gc $File)
$IPCount = $IPCount.count
write "$IPCount unique IP addresses detected."
#Define error actions.
$erroractionpreference = "SilentlyContinue"
#Get content from given IP list.
$colComputers = #(gc $File | sort |Select -unique)
$SourceCount = $colComputers.Count
write "$SourceCount IP's detected."
Function Set-KnownIPs{
Param([Object]$DNSLookupObject)
Switch($DNSLookupObject){
{$_.Source -Match "(108.162.254|141.101.(?:104|105)|199.27.128|173.245(?:53|52|51))"}{$_.HostName = "CloudFlare, Inc."}
{$_.Source -Match "(64.18.[0-18])"}{$_.HostName = "Google, Inc."}
{$_.Source -Match "(192.168|127.0.0)"}{$_.HostName = "Internal Infrastructure"}
}
$DNSLookupObject
}
#Get DNS Results
$Progress=1
$DNSResults = $colComputers | %{
Write-Progress -Activity "Creating a usable 'Blocked IP' list ($Progress/$sourcecount)" -PercentComplete ($Progress/$sourceCount*100) -Status "Please stand by"
try {
($dnsresult = [System.Net.DNS]::GetHostEntry($_))
}
catch {
$dnsresult = "Fail"
}
Set-KnownIPs -DNSLookupObject ([PSCustomObject][Ordered]#{
Source=$_.ToUpper()
HostName=$(if(!([string]::IsNullOrEmpty($dnsresult.HostName))){$dnsresult.HostName})
IPAddress=$(if(!([string]::IsNullOrEmpty($dnsresult.AddressList))){$dnsresult.AddressList[0].ToString()})
})
$Progress++
}
$Keywords = #("Google","Cloudflare","Cloud","Ping",
"Easy-Voyage","McAfee","Pingdom","Panopta","Scoot","Uniglobe",
"Internal")
$Filter = "($(($Keywords|%{[RegEx]::Escape($_)}) -join "|"))"
$DNSLookupFailed = $DNSResults |
?{[string]::IsNullOrEmpty($_.HostName) -and !($_ -match $filter)}
$DNSWithKeyword = $DNSResults |
?{$_ -match $Filter}
$DNSNoKeyword = $DNSResults |
?{!($_.HostName -match $Filter) -and !([string]::IsNullOrEmpty($_.IPAddress))}
#$count = ($DNSResults|?{$_ -match $filter}).count
$count = $SourceCount
#####################
#start Excel.
$a = New-Object -comobject Excel.Application
# set interactive to false so nothing from excel is shown.
$a.DisplayAlerts = $False
$a.ScreenUpdating = $True
$a.Visible = $True
$a.UserControl = $True
$a.Interactive = $True
###########################
#Create sheets in Excel.
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Activate() | Out-Null
#Create a Title for the first worksheet and adjust the font
$c.Cells.Item(1,1)= "Blocked IP's $Date"
$c.Cells.Item(1,1).Font.ColorIndex = 55
$c.Cells.Item(1,1).Font.Color = 8210719
$c.Cells.Item((3+$DNSWithKeyword.Count+1),1) = "IP's not in whitelist"
$c.Cells.Item((3+$DNSWithKeyword.Count+1),1).Font.ColorIndex = 55
$c.Cells.Item((3+$DNSWithKeyword.Count+1),1).Font.Color = 8210719
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1)= "IP's without DNS return"
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1).Font.ColorIndex = 55
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1).Font.Color = 8210719
#######################################
$range = $c.Range("a1","e1")
$range.Style = 'Title'
$range.Select()
$range.MergeCells = $true
$range.VerticalAlignment = -4108
################################
$Linkedin = "https://www.linkedin.com/profile/view?id=96981180" #Look me up! :D
#Define row to be used for linkedin link.
$CounterRow = $Count+5
######################
#Define subjects.
$c.Name = "Blocked IP's ($Date)"
$c.Cells.Item(2,1) = "Given IP"
$c.Cells.Item(2,2) = "Resolved DNS"
$c.Cells.Item(2,3) = "Returned IP"
$c.Cells.Item(2,5) = "$Company"
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+5),1) = "Created by"
########################################
$link = "http://www.$Company"
$link2 = "$Linkedin"
$r = $c.Range("E2")
[void]$c.Hyperlinks.Add($r, $link)
$r = $c.Range("A$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+5)")
[void]$c.Hyperlinks.Add($r, $link2)
###################################
#Define cell formatting from subjects.
$c.Range("A2:E2").Interior.ColorIndex = 6
$c.Range("A2:E2").font.size = 13
$c.Range("A2:E2").Font.ColorIndex = 1
$c.Range("A2:E2").Font.Bold = $True
###################################
#Define the usedrange, excluding header and footer rows
$KeyRange = $c.Range("A3:c$(3+$DNSWithKeyword.Count)")
$NoKeyRange = $c.Range("A$(3+$DNSWithKeyword.Count+2):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+2)")
$NoDNSRange = $c.Range("A$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+4):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)")
$SheetRange = $c.Range("A3:e$(4+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)")
$Investigate = $c.Range("c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+4):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)")
################################
#Set background color for the IP list.
$SheetRange.interior.colorindex = 6
$KeyRange.interior.colorindex = 4
$NoKeyRange.interior.colorindex = 15
$NoDNSRange.interior.colorindex = 8
####################################
#Populate data into spreadsheet
$DNSWithKeyword | Select Source, HostName, IPAddress | Sort HostName -Descending |
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation |
Select -Skip 1 | Clip
$c.Paste($KeyRange,$false)
$DNSNoKeyword | Select Source, HostName, IPAddress | Sort HostName -Descending |
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation |
Select -Skip 1 | Clip
$c.Paste($NoKeyRange,$false)
$DNSLookupFailed | Select Source, HostName, IPAddress | sort Source -Descending|
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation |
Select -Skip 1 | Clip
$c.Paste($NoDNSRange,$false)
############################
ForEach($Cell in $Investigate){
If([String]::IsNullOrWhitespace($Cell.value2)){
$Cell.Item($_) = "N/A"
[void]$cell.Hyperlinks.Add($Cell)
}
}
###########################################################################
#Define borders here.
$xlOpenXMLWorkbook = 51
$xlAutomatic=-4105
$xlBottom = -4107
$xlCenter = -4108
$xlRight = -4152
$xlContext = -5002
$xlContinuous=1
$xlDiagonalDown=5
$xlDiagonalUp=6
$xlEdgeBottom=9
$xlEdgeLeft=7
$xlEdgeRight=10
$xlEdgeTop=8
$xlInsideHorizontal=12
$xlInsideVertical=11
$xlNone=-4142
$xlThin=2
#########
$selection = $c.range("A2:C$(1+$DNSResults.Count-9)")
$selection.select() |out-null
$selection.HorizontalAlignment = $xlRight
$selection.VerticalAlignment = $xlBottom
$selection.WrapText = $false
$selection.Orientation = 0
$selection.AddIndent = $false
$selection.IndentLevel = 0
$selection.ShrinkToFit = $false
$selection.ReadingOrder = $xlContext
$selection.MergeCells = $false
$selection.Borders.Item($xlInsideHorizontal).Weight = $xlThin
#############################################################
#Define the usedrange for autofitting.
$d = $c.UsedRange
#################
#Make everything fit in it's cell.
$d.EntireColumn.AutoFit() | Out-Null
####################################
$c.usedrange | Where{$_.Value2 -match "(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)"} |
ForEach{$IPLink = "http://who.is/whois-ip/ip-address/$($Matches[1])";[void]$c.Hyperlinks.Add($_, $IPLink)}
#Define html code for Excel save to .htm.
$xlExcelHTML = 44
#################
#Save final result as an .xlsx file.
$b.SaveAs("$FileXML")
#####################
#Save final result as a .htm file
$b.SaveAs("$FileHTML",$xlExcelHTML)
###################################
In powershell 5.1 you can use
Resolve-DnsName

How to put a header to csv file generated by Powershell script

I got this Powershell script that queries users that have not changed their password for 24 hours. The query redirects the output to csv file. Below are the Powershell script and batch script:
Powershell script:
$root = [ADSI]''
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"
$searcher.sizelimit = 5000
[Void]$searcher.PropertiesToLoad.Add("cn")
[Void]$searcher.PropertiesToLoad.Add("samAccountName")
[Void]$searcher.PropertiesToLoad.Add("pwdLastSet")
$users = $searcher.findall()
$UserOU = "OU=Mountain,DC=Atlanta,DC=ga"
$PWDays = (Get-Date).AddDays(-1)
$UserCount = 0
$UserPW = 0
foreach($user in $users)
{
if ($user.path -like "*$UserOU")
{
$usercount = $UserCount
if ([datetime]::FromFileTime(($user.properties.pwdlastset)[0]) -le $PWDays)
{
$UserPW = $UserPW + 1
Write-Host $user.Properties.cn
}
}
}
Batch script:
powershell.exe d:\temp\query.ps1 > D:\temp\query.csv
My question is: How do I put change the script to put header for username in the the csv output file?
The header may simple be 'Username' not necessarily Firstname and Lastname.
Any reason why you aren't using Export-Csv? You can just pipe your objects into it and it will include headers. Something along the lines of
$users |
? { $_.Path -like "*$UserOU" } |
? { [datetime]::FromFileTime(($user.properties.pwdlastset)[0]) -le $PWDays } |
% { $_ | Add-Member -PassThru NoteProperty Username $_.Properties.cn } |
select Username |
Export-Csv D:\temp\query.csv
might work. (Hint: The pipeline is more fun than the loop :))
Not sure (never have user PS) but I guess that sticking
Write-Host "Username"
before the foreach, might do the trick