4

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
Matt Hamende
  • 139
  • 2
  • 4
  • 16

2 Answers2

9

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() }
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
1

Just an update in case anyone is looking in 2021.

This command/syntax worked for me in 2008 R2 (PowerShell version 2.0) (I was able to piece this together from this page, as well as others).

Finds all jobs over 30 minutes and deletes them:

Get-wmiobject win32_printjob 
| Where-Object {[System.Management.ManagementDateTimeConverter]::ToDateTime($_.TimeSubmitted) -lt (Get-Date).addminutes(-30)} 
| ForEach-Object { $_.delete() }*
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • It may be useful to also add why the accepted answer is no longer valid. Does it give an error? Rely on outdated APIs? – Jeremy Caney Jul 01 '21 at 01:15