我有下面的脚本。如果我取消注释评论#3
的行,则会收到错误
Exception calling "Delete" with "0" argument(s): ""
At Z:\Scripts\Powershell\Remove-UserProfile.ps1:48 char:21
+ $Profile.Delete()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
无论我是否使用#1
或#2
中的格式询问WMI。如果我对#3
发表评论并取消注释#4
,则会收到错误
Remove-WmiObject :
At Z:\Scripts\Powershell\Remove-UserProfile.ps1:49 char:21
+ Remove-WmiObject -InputObject $Profile
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Remove-WmiObject], COMException
+ FullyQualifiedErrorId : RemoveWMICOMException,Microsoft.PowerShell.Commands.RemoveWmiObject
无论Get-WMIObject
的查询字符串如何。
我能在网上找到的所有东西 - 包括其他几个SO问题 - 暗示这些方法中的任何一种都应该有效,但似乎都没有。我已经检查了目标配置文件是否已加载,而不是。为什么我不能使用WMI删除用户配置文件?我可以做什么 工作,并且不涉及从第三方下载实用程序(我们的信息安全&#34;团队不允许)?< / p>
脚本:
function Remove-UserProfile {
<#
.SYNOPSIS
Removes user profiles from computers
#>
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="High")]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String[]]$ComputerName = $env:ComputerName,
[Alias("UserName","sAMAccountName")]
[String]$Identity,
[Int]$Age,
[Switch]$DomainOnly
)
BEGIN {
$NoSystemAccounts = "SID!='S-1-5-18' AND SID!='S-1-5-19' AND SID!='S-1-5-20' " # Don't even bother with the system accounts.
if ($DomainOnly) {
$SIDQuery = "SID LIKE '$((Get-ADDomain).DomainSID)%' " # All domain account SIDs begin with the domain SID
} elseif ($Identity.Length -ne 0) {
$SIDQuery = "SID LIKE '$(Get-UserSID -AccountName $Identity)' "
}
$CutoffDate = (Get-Date).AddDays(-$Age)
$Query = "SELECT * FROM Win32_UserProfile "
}
PROCESS{
ForEach ($Computer in $ComputerName) {
Write-Verbose "Processing Computer $Computer..."
if ($SIDQuery) {
$Query += "WHERE " + $SIDQuery
$FilterStr = $SIDQuery
} else {
$Query += "WHERE " + $NoSystemAccounts
$FilterStr = $NoSystemAccounts
}
Write-Verbose "Querying WMI using '$Query' and filtering for profiles last used before $CutoffDate ..."
#1 $Profiles = Get-WMIObject -Query $Query | Where-Object { [Management.ManagementDateTimeConverter]::ToDateTime($_.LastUseTime) -lt $CutoffDate }
#2 $Profiles = Get-WMIObject -ComputerName $Computer -Class Win32_UserProfile -Filter $FilterStr | Where-Object { [Management.ManagementDateTimeConverter]::ToDateTime($_.LastUseTime) -lt $CutoffDate }
ForEach ($Profile in $Profiles) {
if ($PSCmdlet.ShouldProcess($Profile)) {
#3 $Profile.Delete()
#4 Remove-WmiObject -InputObject $Profile
}
}
}
}
END {}
}
答案 0 :(得分:1)
编辑: 您必须以管理员身份运行脚本。