Modify date format of file name (powershell)

Hey Experts, in the script below, a log file is created with the file name that relates to the date the script is ran (Stale_Users_%Year%_%DayofYear%).  What I would like to see is the Month Day Hour Minute (1208_1114) if the script was ran Dec 8th at 11:14am.  The year isn't necessary.  I tried the %m%d%H%M and -uFormat with the $date variable but I just haven't been able to make it happen.  Any help would be appreciated.

Import-Module ActiveDirectory

$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$date = Get-Date
$todaysLog = $logPath + $date.Year + "_" + $date.DayOfYear + ".log"

Open in new window

LVL 9
samiam41Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

oBdACommented:
$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$date = Get-Date
$todaysLog = $logPath + $date.ToString('MMdd_HHmm') + ".log"

Open in new window

Bill PrewIT / Software Engineering ConsultantCommented:
Give this a try.

$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$date = Get-Date -format 'MMdd_hhmm'
$todaysLog = $logPath + "_" + $date + ".log"

Open in new window


»bp
oBdACommented:
'hh' is not a good idea. That's 12-hour format, so "05" could mean 5 in the morning or 5 in the evening.
Acronis True Image 2019 just released!

Create a reliable backup. Make sure you always have dependable copies of your data so you can restore your entire system or individual files.

Bill PrewIT / Software Engineering ConsultantCommented:
Good catch oBdA.


»bp
Dustin SaundersDirector of OperationsCommented:
Just remember if you don't add the year you're going to get overlap each time the year rolls over in your logs unless you are purging the directory regularly.
samiam41Author Commented:
Thanks for the scripts guys and advice about the year in the script (I will need to add this).

Experts, is there anyway to create a log file every time I run this?  I can't seem to get a new log file created.
Jason CrawfordTransport NinjaCommented:
oBdACommented:
You have to elaborate on "I can't seem to get a new log file created.".
What/how are you trying to log, and what is not working?
samiam41Author Commented:
@oBdA, when I run the powershell script to test the new date feature, a new log file isn't created in the directory.  Thus, I was asking if there was a away for the script to run so that it creates a log file so that it says "no stale accounts found", please.
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
What you showed us up to now, and the question is about, is only about generating the log file name, not writing anything into it. But if you just want to create an empty log file each time, use something like $null | Out-File $todaysLog (as one of many ways to do that).
oBdACommented:
samiam41,
your question was about creating a new file name, and that was all that was in the code snippet you provided. Then you said, "a new log file isn't created in the directory", without giving any further information - how can we help you if you don't provide the script that is supposed to log?
A file containing a certain text is easily created:
"no stale accounts found" | Set-Content $todaysLog

Open in new window

samiam41Author Commented:
I appreciate the feedback and opportunity to clarify my question.  The original request was to have the output log named by the date ran.  No question there.  Subsequently, when testing out the experts coding, I wasn't seeing a new file being created with this new file name.  Thus, to help with the trouble-shooting, I asked for the log file to have something (such as "no stale accounts found") entered into the new text file.

Hopefully that clarifies the question.  I'm just trying to figure out why the text file isn't being created when I run it in PS.  If you have a different method of trouble-shooting versus a null entry or text being entered like "no stale accounts found" in the event that the script has been run and there aren't any accounts there but you still want to test, I'm all ears and eyes for what you suggest as I'm here to learn from the experts and may not know what to ask (or post).

TLDR: new file isn't being created when using that modified script/trying to use a way of forcing a log file to be generated
oBdACommented:
Well, we can't help you identify the cause of the log file not being created if we have no idea how you're implementing the logging in the first place.
You'll get a completely empty file (Qlemo's method above will create a 2-byte file with CRLF in it), btw., with
$Item = New-Item -Path $todaysLog -ItemType File -Force

Open in new window

samiam41Author Commented:
Import-Module ActiveDirectory

$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$date = Get-Date
$todaysLog = $logPath + $date.Year + "_" + $date.DayOfYear + ".log"

function WriteLog($message)
{
    $message = (Get-Date).ToShortTimeString() + " - " + $message
    Add-Content -Path $todaysLog -Value $message
}

$disabledOU = "OU=Computers,DC=local"

$computers = Get-ADComputer -SearchBase "OU=Depts,DC=local" -Filter * -Properties DistinguishedName, SAMAccountName, lastLogonTimeStamp | ?{[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt (Get-Date).AddDays(-49)}
foreach ($computer in $computers)
{
    try {
        Disable-ADAccount -Identity $computer.DistinguishedName 
        WriteLog("Disabled $($computer.SAMAccountName)")
    } catch {
        WriteLog("Failed to disable $($computer.SAMAccountName)")
    }
    
    try {
        Move-ADObject -Identity $computer.DistinguishedName -TargetPath $disabledOU 
        WriteLog("Moved $($computer.SAMAccountName) to $disabledOU")
    } catch {
        WriteLog("Failed to move $($computer.SAMAccountName) to $disabledOU")
    }
}

Open in new window

samiam41Author Commented:
Once I added that entry
$Item = New-Item -Path $todaysLog -ItemType File -Force

Open in new window

, the log file suddenly shows up WITH the new naming scheme when the script is ran.  Progress.  Now I'm guessing there weren't any computers that met the stale requirements which was causing the log file to not be created.  Done and done.  I knew it just needed to be forced to be created to show the new file name.  Thanks everyone.
oBdACommented:
Seems like you want something like this.
And note that Powershell functions are called with named arguments just like cmdlets, not with arguments in round brackets like in VBScript or whatever.
Import-Module ActiveDirectory

$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$Date = Get-Date
$TodaysLog = $logPath + $Date.ToString('YYYYMMdd_HHmm') + ".log"
$FilterDate = $Date.AddDays(-49)

function WriteLog($message) {
    $message = (Get-Date).ToShortTimeString() + " - " + $message
    Add-Content -Path $TodaysLog -Value $message
}

$disabledOU = "OU=Computers,DC=local"

$StaleComputers = Get-ADComputer -SearchBase "OU=Depts,DC=local" -Filter * -Properties DistinguishedName, SAMAccountName, lastLogonTimeStamp |
	Where-Object {[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt $FilterDate}

If ($StaleComputers) {
	ForEach ($computer in $StaleComputers) {
		Try {
			Disable-ADAccount -Identity $computer.DistinguishedName -ErrorAction Stop
			WriteLog -Message "Disabled $($computer.SAMAccountName)"
		} Catch {
			WriteLog -Message "Failed to disable $($computer.SAMAccountName): $($_.Exception.Message)")
		}
    
		Try {
			Move-ADObject -Identity $computer.DistinguishedName -TargetPath $disabledOU -ErrorAction Stop
			WriteLog -Message "Moved $($computer.SAMAccountName) to $disabledOU"
		} Catch {
			WriteLog -Message "Failed to move $($computer.SAMAccountName) to $($disabledOU): $($_.Exception.Message)"
		}
	}
} Else {
	WriteLog -Message "No stale computer accounts found."
}

Open in new window

samiam41Author Commented:
oBdA, I know we are way outside the scope of the OQ so I'm comfortable closing this one out and opening a new one to go through what has been discovered.  Your call.  Below are the error messages that I get when I run the script (after I sub in my OU info).

At line:23 char:11
+         } Catch {
+                 ~
Missing closing '}' in statement block.
At line:19 char:41
+     ForEach ($computer in $StaleComputers) {
+                                            ~
Missing closing '}' in statement block.
At line:18 char:22
+ If ($StaleComputers) {
+                      ~
Missing closing '}' in statement block.
At line:24 char:94
+ ... ption.Message)")
+                    ~
Unexpected token ')' in expression or statement.
At line:25 char:3
+         }
+         ~
Unexpected token '}' in expression or statement.
At line:33 char:2
+     }
+     ~
Unexpected token '}' in expression or statement.
At line:34 char:1
+ } Else {
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndCurlyBrace
oBdACommented:
Sorry, missed a closing brackets:
Import-Module ActiveDirectory

$logPath = "C:\Tools\Logs\Stale_Users_"  #directory to log output
$Date = Get-Date
$TodaysLog = $logPath + $Date.ToString('YYYYMMdd_HHmm') + ".log"
$FilterDate = $Date.AddDays(-49)

Function WriteLog($message) {
    $message = (Get-Date).ToShortTimeString() + " - " + $message
    Add-Content -Path $TodaysLog -Value $message
}

$DisabledOU = "OU=Computers,DC=local"

$StaleComputers = Get-ADComputer -SearchBase "OU=Depts,DC=local" -Filter * -Properties DistinguishedName, SAMAccountName, lastLogonTimeStamp |
	Where-Object {[DateTime]::FromFileTime($_.lastLogonTimeStamp) -lt $FilterDate}

If ($StaleComputers) {
	ForEach ($Computer in $StaleComputers) {
		Try {
			Disable-ADAccount -Identity $Computer.DistinguishedName -ErrorAction Stop
			WriteLog -Message "Disabled $($Computer.SAMAccountName)"
		} Catch {
			WriteLog -Message "Failed to disable $($Computer.SAMAccountName): $($_.Exception.Message)"
		}
    
		Try {
			Move-ADObject -Identity $Computer.DistinguishedName -TargetPath $DisabledOU -ErrorAction Stop
			WriteLog -Message "Moved $($Computer.SAMAccountName) to $($DisabledOU)"
		} Catch {
			WriteLog -Message "Failed to move $($Computer.SAMAccountName) to $($DisabledOU): $($_.Exception.Message)"
		}
	}
} Else {
	WriteLog -Message "No stale computer accounts found."
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
samiam41Author Commented:
Thank you experts for your patience and willingness to work through this question.  Very much appreciated.
samiam41Author Commented:
**minor tweak to the script**

$TodaysLog = $logPath + $Date.ToString('YYYYMMdd_HHmm') + ".log"

I had to use lower case y's.

$TodaysLog = $logPath + $Date.ToString('yyyy_MMdd_HHmm') + ".log"
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.