Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Script to query and delete print jobs older than "x" days

I started putting this PowerShell Script together, the hope would be to replace some tasks that are currently carried out manually

I'm using the

get-Date.AddDays()

function

I'm using the ISE to build the script and in testing I get output if I single out the 'starttime' property, but this seems to be a catch all because the values all come up null, ideally I'd like to use the 'timesubmitted' property, but the date seems to output in an odd that I don't think is being read correctly because my queries with 'timesubmitted' always come up empty

it comes out in this format, if you do an open query

20120416030836.778000-420

here's what I have so far.

disregard the | 'format-table' function that's just so I can see if I'm getting the desired output

#Clears Old Print Jobs on Specified server

#Sets Execution Policy for Script to run
Set-ExecutionPolicy RemoteSigned -Force

#establishes variable for cutoff date
$d = Get-Date
$old = $d.AddDays(-4)

#Queries WMI and retrieves print jobs
Get-WmiObject -class win32_printjob -namespace "root\CIMV2" | where-object {$_.timesubmitted -lt
"$old"} | ft caption,document,jobid,jobstatus,owner,timesubmitted
like image 732
Matt Hamende Avatar asked Feb 21 '23 19:02

Matt Hamende


1 Answers

In PowerShell every WMI instance has a ScriptMethod that you can use to convert the dates from WMI format to .NET format:

Get-WmiObject Win32_PrintJob | 
Where-Object { $_.ConvertToDateTime($_.TimeSubmitted) -lt $old } |
Foreach-Object { $_.Delete() }
like image 57
Shay Levy Avatar answered Apr 26 '23 23:04

Shay Levy