This is the folder structure for the daily server CMDB true up reports. The code snippet assumes that the script it’s part of is deployed as a PowerShell scheduled job running on the server that provides the file share and therefore absolute paths are used.
Create the Folder Structure and Implement the File Naming scheme:
To organize the daily reports the script creates a folder structure to hold the daily reports and to accept input from an input folder if needed. I also wanted to email a monthly report to management at the first of each month.
# Start Folder and File Name structure
# Get the current date in the format YEAR-MONTH-DAY
$fdate = Get-Date -Format "yyyy-MM-dd"
# Create a Booleam variable to be used to decide if a
# monthly report is due.
[System.Boolean]$monthlyReport = $false
# Check if this is the first of the month and report
# should be emailed to management.
If ([string]($fdate.Split('-')[2]) -eq '01') {
$monthlyReport = $true
}
#
# Create the filename using the full date
# All daily files for a given month
# will be stored in a folder for that month
$filename = [String]$fdate + "_svr_cmdb_report.xlsx"
#
# Now create the folder structure if it doesn't exist
# The key is that the New-Item command will not
# overwrite if creating a directory
$rootpath = "D:\PowerShell_Scripts"
$inpath = "$rootpath\inventory\input"
$outpath = "$rootpath\inventory\out\" + $fdate.Split('-')[0] + '\' + $fdate.Split('-')[1] +'\'
$path = $fulloutpath + $filename
# Does not overwrite if $outpath exists
New-Item -Path $outpath -ItemType Directory -Force
#
# clear out an old file for a new run for
# the current date if an old report for the day exists
if (Test-Path $path) {
Remove-Item $path -ErrorAction Ignore
Write-EventLog -LogName "Application" -Source "CustomScripts" -EventId 1000 -EntryType Information -Message "Removing report file for new run"
}
#
# End Folder and File Name structure
Example: Assuming that the date is 2020-04-13. This code snippet creates a folder structure that looks like this: D:\PowerShell_Scripts\inventory\out\2020\04\
The report name would be: 2020-04-13_srv_cmdb_report.xlsx