Hey, Scripting Guy! How Can I Use Windows PowerShell to Delete All the Files in a Folder Older Than 90 Days? – Hey, Scripting Guy! Blog – Site Home – TechNet Blogs


From: Hey, Scripting Guy! How Can I Use Windows PowerShell to Delete All the Files in a Folder Older Than 90 Days? – Hey, Scripting Guy! Blog – Site Home – TechNet Blogs.

Hey, Scripting Guy! How Can I Use WindowsPowerShelltoDeleteAll the Files in a Folder Older Than 90 Days?

Hey, Scripting Guy! Question

Hey, Scripting Guy! In WindowsPowerShell, how can I determine the number of days difference between two dates? I want to be able todeleteall the files in a folder that are more than 90 days old.

— JN

SpacerHey, Scripting Guy! AnswerScript Center

Hey, JN. You know, today is October 31stand, in the US at least, it’s the day when the dark underworld takes over: witches parade through the streets, cackling and laughing; ghosts and goblins cavort on the front lawn; devils and demons come up and ring your doorbell; it’s the one day out of the year when evil truly reigns supreme. In other words, it’s – no, it’s not the Scripting Editor’s birthday (although thatwouldexplain a lot, wouldn’t it?). Instead, it’s Halloween.


Note. We just double-checked and it’snotthe Scripting Editor’s birthday; her birthday is in July. For those of you who like to plan ahead, however, sheisbeginning to run low on eye of newt and toe of frog, although she seems to still have plenty of wool of bat and tongue of dog.

In the US, Halloween is marked by children dressing up in costumes (the scarier the better) and going around ringing peoples’ doorbells and asking for candy. You know, we’re going to gotriple-check that date. Now that we think about it, we’re pretty sure that’s exactly what the Scripting Editor did on her last birthday.

For those of you unfamiliar with the holiday, the primary symbol of Halloween is the jack-o-lantern, a symbol you make by hollowing out a pumpkin, carving a face into the hollowed-out gourd, then placing a lighted candle inside. According to legend, the jack-o-lantern got its start many, many years ago, when a drunkard and ne’er do well named Jack tricked the Devil into climbing a tree; once the Devil was safely ensconced in the branches, Jack carved a cross into the tree trunk, something that prevented the Devil from climbing down. Jack agreed to help the Devil down on one condition: that the Devil would never bother him again.

A few years later Jack died, and when he went up to heaven he was denied entrance because of his wicked ways. That sent him … downstairs … where he was refused entrance because he had previously tricked the Devil. As a result, Jack was condemned to roam the earth forever although, as a sort of consolation prize, the Devildidgive him a lighted candle to help him make his way through the dark.

You know what? We’re going toquadruple-check that date. That story sounds like it was copied, word-for-word, from the Scripting Editor’s resume.

At any rate, and in the spirit of the occasion, the Scripting Guy who writes this column decided to do something frightening and horrifying for today’s column. And what could be more frightening or more horrifying than a WindowsPowerShellscript that deletes all the files in a folder more than 90 days old?!?

Well, as it turns out, just abouteverythingis more frightening than that:

Before we explain how this works, let’s look at a simpler example, one that merely subtracts two dates. Here’s whatthatsample script looks like:

As you can see, there’s nothing very complicated about this particular script. In the first line, we use theGet-Datecmdlet to retrieve the current date and time and store it in a variable named $x. In line 2, we use the Get-Date cmdlet to retrieve a date-time value equivalent to January 1, 2007. Note that we didn’t specify a time when retrieving this second value; consequently, our date-time instance will be given a default time of 12:00:00 AM. What if wewantedto specify a particular time? No problem; as the good folks at Nike would say, just do it:

OK, so we have two date-time values, $x and $y; now what? Well, if we want to determine the time interval between these two dates all we have to do is subtract one from the other. Subtract $y from $x and look what you get back:

Right there, at the top of the list, is the value we’re looking for; it turns out that there are 302 days between the current date (October 30, 2007, the day this column was written) and January 1, 2007. Not bad, huh?

Well, OK, you’re right: it’s not bad, but it’s not necessarily all that good, either. That’s because we have a lot of extraneous property values (Hours, Minutes, Second, Milliseconds, etc.) that wearen’tinterested in. But that’s all right; let’s modify the last line of our script and see what happens:

What have we done here? Well, we’re still subtracting $y from $x; the only difference is that, this time, we’re performing this little bit of date arithmetic inside a pair of parentheses. Why? Well, we need to do two things here. First, we need to subtract one date value from another ($x – $y); that’s going to give us an instance of the .NET Framework classSystem.TimeSpan.

Second, we want to display just the value of theDaysproperty for that TimeSpan object. To ensure that we first get the TimeSpan object and onlythentry to retrieve the value of the Days property we enclose our little arithmetical equation inside a set of parentheses.PowerShellalways carries out commands in parentheses before it does anything else; thus it’s going to perform the date calculation first and then, once it has the TimeSpan object, go out and retrieve the value of the Days property.

Will that really work? See for yourself:

Now, at long last, we’re ready to talk about the script that deletes all the files in a folder that are more than 90 days old. That script starts out by using theGet-ChildItemcmdlet to retrieve a collection of all the objects found in the folder C:\Scripts, storing that collection in a variable named $a:


Note. What’s that? Some of you would like to perform this same task against all the files in any subfolders of C:\Scripts as well? Okey-doke; in that case, just add the–recurseparameter to your Get-ChildItemcommand:

Next we set up a foreach loop to loop through all the items in our collection. Inside that loop, the first thing we do is this:

When we first showed you this script you might have looked at this line of code and said, “Uh-oh.” Now, however, you should be able to see exactly what we’re doing here.

So whatarewe doing here? Well, for starters, we’re using Get-Date to retrieve the current date and time. (Note that Get-Date is in a nested pair of parentheses; that ensures that we get the current date and time before we do anything else.) Once wehavethe current date and time we then grab the value of the first item’sCreationTimeproperty and subtract that from the value retrieved by Get-Date. That equation, as we know, is going to return a TimeSpan object; once we have that object, we then skim off the value of the Days property and store that value in a variable named $y.

And you’re right: it onlysoundscomplicated. In reality, it’s fairly straightforward.

That brings us to this line of code:

There are two things going on here. First, the variable $y tells us the number of days between the current date and time and the date and time that the first item in our collection was created. What we want to do is check to see if this value is greater than (-gt) 90; if it is, then this item is acandidatefor deletion.

Why just a “candidate” for deletion? Well, we only want todeletefiles; we don’t want todeletefolders. That’s where this little bit of code comes in:

Here we’re simply making sure that thePsISContainerproperty is not equal to (-ne) True (represented by thePowerShellbuilt-in variable $True). If PsISContaineristrue then that means we’re working with a folder, and we don’twantto work with (ordelete) folders. If PsISContainer is False, then that’s fine: that means we’re dealing with a file.

So suppose wedohave a file that happens to be more than 90 days old; what then? Well, in that case, all we have to do is call theDeletemethod and deleted the thing:

And then it’s back to the top of the loop, where we repeat the process with the next item in the collection.

Now, admittedly, we might have been able to simplify this script a tiny bit. (Or maybe not; that’s more an aesthetic judgment than anything else.) However, we went this particular route so we could kill two birds with one stone: we could show you the basics ofPowerShelldate arithmeticandwe coulddeleteall the old files in a folder. Consider this our Halloween treat to the scripting world: two for the price one.


Note. No, we didn’treallykill two birds with one stone. That was all done with special effects that combined cleverly-costumed stunt men and computer animation.

Anyway, we hope that answers your question, JN. As for the Scripting Guy who writes this column, he’s going to go home and hand out candy to the trick-or-treaters, despite the fact that he doesn’t really like Halloween. Is that because he’s opposed to devils and demons? Oh, heck no; he works at Microsoft, remember? No, it’s just that Halloween used to be a holiday exclusively for kids, and now many adults have co-opted the day for themselves. In fact, many parents don’t even allow their children to go trick-or-treating; they’re afraid the kids will come back with poisoned candy. (The number of documented cases where children have come home from trick-or-treating with poisoned candy? Zero.)

Instead, the parents hire a babysitter, make the kids stay at home, thenthe parentsdress up in costumes and go out and party. The Scripting Guy who writes this column thinks that’s a terrible thing to do to children, which is why he doesn’t really like Halloween anymore.

By contrast, the Scripting EditorlovesHalloween; she says it’s the one day out of the year when she can “really be herself.” You know what? We’re going to go check that date one last time ….


Editor’s Note: Just to set the record straight, the Scripting Editor was not born on October 31. Not that it would mean anything negative if she had been – there are plenty of perfectly normal people out there who were born on Halloween. As for how the Scripting Editor spends Halloween? She spends it handing out candy – with the help of the Scripting Dog – to all the kids whose parentsdo let them trick-or-treat. (One year, only about five years ago, that wound up being over 100 kids.)

448 total views, no views today

Forgotten Command: systeminfo | Techish.net


From: Forgotten Command: systeminfo | Techish.net.

Time after time, I am asked something about a computer –  How much memory does it have?  What Windows updates are installed?  What type of network connectivity does it have…  And time after time, I send a response telling whoever is asking me to use a simple (but widely forgotten) command:

What does systeminfo command give you?

This tool displays operating system configuration information for
a local or remote machine, including service pack levels.

It’s a very handy tool for some quick information on a computer!

795 total views, 1 views today

PowerShell script to change administrator password on a list of machines – Ying LiMVP at myITforum.com


From: PowerShell script to change administrator password on a list of machines – Ying LiMVP at myITforum.com.

PowerShell script to change administrator password on a list of machines

Here is a PowerShell script to change local administrator (or any account interested) password on a list of remote machines. I am using my friend Don Hite’s VB Script as a starting point. So as always my hat off to Don!

$erroractionpreference = “SilentlyContinue”

$a = New-Object -comobject Excel.Application
$a.visible = $True

$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)

$c.Cells.Item(1,1) = “Machine Name”
$c.Cells.Item(1,2) = “Password Changed”
$c.Cells.Item(1,3) = “Report Time Stamp”

$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True

$intRow = 2

foreach ($strComputer in get-content C:\MachineList.Txt)
$c.Cells.Item($intRow,1)  = $strComputer.ToUpper()

# Using .NET method to ping test the servers – This is very cool!
$ping = new-object System.Net.NetworkInformation.Ping

$Reply = $ping.send($strComputer)
if($Reply.status -eq “success”)
# This is the Key Part
$admin=[adsi](“WinNT://” + $strComputer + “/administrator, user”)

$admin.psbase.invoke(“SetPassword”, “Whatever1”)

#$admin.psbase.CommitChanges() – I am surprised that I don’t have to do this!

# If this is for AD account, we could use PasswordLastchanged attribute. But WinNT provider does not #support the PasswordLastChanged attribute!

# I was trying to use passwordage attribute value but somehow I found it give you the value for last time, #may be because there is a delay for this attribute to propagate. So I made an “executive” decision to test #if passwordage is $null – so this may not be 100% accurate.

$pwage = $admin.passwordage

If($pwage -ne “0”)
$c.Cells.Item($intRow,2).Interior.ColorIndex = 4
$c.Cells.Item($intRow,2) = “Yes”
$c.Cells.Item($intRow,2).Interior.ColorIndex = 3
$c.Cells.Item($intRow,2) = “No”
$c.Cells.Item($intRow,2).Interior.ColorIndex = 3
$c.Cells.Item($intRow,2) = “Not Pingable”

$c.Cells.Item($intRow,3) = Get-Date

$Reply = “”
$pwage = “”
$intRow = $intRow + 1


Posted: Aug 23 2007, 11:23 AM by yli628 | with 3 comment(s)

Filed under: 

533 total views, 2 views today

HTML Snippets Powered By : XYZScripts.com