我試圖創建一個腳本來檢測長達15天的域用戶配置文件並刪除它們。這將捆綁在一個工作中,在運行之前將會註銷任何閒置會話。腳本沒有正確地將WMI對象分配給陣列
我知道這通常是通過GPO完成的,但是由於各種原因它不適合用於這個特定業務領域。
這裏是我的代碼:
#Assign how old the user profile must be for deletion
[int]$NoOfDays = 15
#Get WMI object where it is a domain account and over 15 days old
$Objects = @(Get-WmiObject -Class Win32_UserProfile | Where {
(!$_.Special) -and
$_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-15)
})
if ($Objects -eq $null) {
#If no users returned, write to host.
Write-Host "no profiles found for deletion"
} else {
#If users are found, do the following
foreach ($Object in $Objects) {
Write-Host "'$($object.LocalPath)' has been identified for deletion"
}
foreach ($Object in $Objects) {
try {
Write-Host "Attempting to delete profile '$($Object.LocalPath)'"
Remove-WmiObject
Write-Host "Deleted profile '$($Object.LocalPath)' successfully."
} catch {
Write-Host "Unable to delete profile '$($Object.LocalPath)'" -ErrorAction Continue
}
}
}
沒有輸出,它只是返回命令沒有錯誤行,立竿見影。
我試圖註釋掉刪除配置文件的位,在每個語句的第一個語句之後結束else,看看刪除了哪些內容,但它沒有起作用。
它似乎對刪除-WmiObject可以cmdlet的一個部分的輸入參數在上面的代碼中給定的被錯過。 –
@Andrei Odegov對不起,謝謝你指出。我設法使刪除工作正常。 –