How to handle Null messages in Foreach loops

by johnkeng at 2012-10-22 10:58:27

This is a noob question I hope someone can shed some knowledge on.

I’m working on a script that will compare the home directory of each user and move it to a new file share server.

$users=import-csv c:\homedir_cleanup.csv

foreach ($name in $Users) {
get-aduser $name -properties homedirectory | %{copy-item -recurse $.homedirectory -destination \172.22.39.17\homedir}
get-aduser $name -properties homedirectory | %{remove-item -recurse $
.homedirectory -force}
}


However there are numerous accounts that don’t have home directories which leads to null path errors. Is there a way to suppress these messages or write them to a log.txt file for troubleshooting? I understand powershell isn’t a "true" programming language, but I’d like to know how others handle these scenarios.

Cheers,
by DonJ at 2012-10-22 11:05:22
Sure - just use an If() construct to compare it to $null. If in fact it’s NULL (as opposed to an empty string, or ‘’), then you’ll get a true comparison.


$user = Get-ADUser $name -properties homedirectory
if ($user.homedirectory -ne $null) {
# do other stuff here - you’ve got a home dir
} else {
# it’s null - log it or whatever
}
by Lembasts at 2012-10-22 14:05:56
[quote="johnkeng"] I understand powershell isn’t a "true" programming language,
[/quote]
Just a correction here - it IS a "true" programming language by any definition :slight_smile:
by DonJ at 2012-10-22 14:15:21
Well, probably depends on how you define "programming language," I suppose. A lot of C++ guys wouldn’t agree ;). But it suffices for its task.