Dav*_*idG 7 windows powershell scripting wmi
我有这个删除配置文件脚本,提示输入用户名并从列出的每台计算机中删除它.删除配置文件和"用户登录"部分都在工作,但是"在名为$ UserName的$ Computer上找不到配置文件"的部分不是.我在两台计算机上运行我的脚本,并成功删除了我的配置文件.我重新创建了我的个人资料(已登录)并保持登录到一个而不是另一个.我再次运行它,它给我"用户登录"的消息.对于另一台计算机,它刚刚删除了配置文件,但未显示"未找到配置文件"消息.它只是跳过它并且什么也没显示.我已将"if"更改为"else"但是,当我这样做时,它会显示多行"找不到配置文件",包括之前删除配置文件的计算机.
这是大多数脚本派生自的链接. http://techibee.com/powershell/powershell-script-to-delete-windows-user-profiles-on-windows-7windows-2008-r2/1556.通过评论,没有其他人似乎对这一部分有任何问题.
我在PowerShell中没有太多的知识,这只是根据我的需要从我发现的其他脚本拼凑而成.我们的环境是Windows 7和Server 2008 R2.非常感谢任何帮助.
$UserName=Read-host "Please Enter Username: "
$ComputerName= @("computer1","computer2")
foreach($Computer in $ComputerName) {
Write-Verbose "Working on $Computer"
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$Profiles = Get-WmiObject -Class Win32_UserProfile -Computer $Computer -ea 0
foreach ($profile in $profiles) {
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$profilename = $objuser.value.split("\")[1]
if($profilename -eq $UserName) {
$profilefound = $true
try {
$profile.delete()
Write-Host -ForegroundColor Green "$UserName profile deleted successfully on $Computer"
} catch {
Write-Host -ForegroundColor Yellow "Failed to delete the profile, $UserName logged on to $Computer"
}
}
}
if(!$profilefound) {
Write-Host -ForegroundColor Cyan "No profiles found on $Computer with Name $UserName"
}
} else {
write-verbose "$Computer Not reachable"
}
}
Run Code Online (Sandbox Code Playgroud)
PowerShell 有许多应避免重复使用的自动变量。
$Profile
是其中之一,它包含适用于当前会话的配置文件脚本的路径。
使用任何其他变量名称(即。$userprofile
),你会没事的:
foreach ($userprofile in $profiles) {
$objSID = New-Object System.Security.Principal.SecurityIdentifier($userprofile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$profilename = $objuser.value.split("\")[1]
if($profilename -eq $UserName) {
$profilefound = $true
try {
$userprofile.delete()
Write-Host -ForegroundColor Green "$UserName profile deleted successfully on $Computer"
} catch {
Write-Host -ForegroundColor Yellow "Failed to delete the profile, $UserName logged on to $Computer"
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
279 次 |
最近记录: |