powershell - 用于从远程计算机中删除几个本地用户的 Powershell 脚本
问题描述
我正在尝试删除远程计算机上的本地用户帐户,其中主机名和用户名位于 csv 文件中。
下面的代码会起作用吗?
$hostdetail = Import-CSV C:\Users\oj\Desktop\Test\hosts.csv
ForEach ($item in $hostdetail) {
$hostname = $($item.hostname)
$username = $($item.username)
$computer = $hostname
#Test network connection before making connection and Verify that the OS Version is 6.0 and above
If ((!(Test-Connection -comp $computer -count 1 -quiet)) -Or ((Get-WmiObject -ComputerName $computer Win32_OperatingSystem -ea stop).Version -lt 6.0)) {
Write-Warning "$computer is not accessible or The Operating System of the computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
}
else {
Invoke-Command -ComputerName $computer -ScriptBlock $scriptBlock
}
}
$scriptBlock = {
function Remove-UserProfile {
Remove-LocalUser -Name $username
}
Remove-UserProfile
}
解决方案
在调用命令之前调用$scriptblock。您应该通过-ArgumentsList参数传递$username 。$Args[0]将是-ArgumentsList中第一个参数的变量。
Powershell 从上到下读取。如果您将请求的对象或函数放在其当前正在读取的位置下方,则 powershell 不会知道它在那里。
$hostdetail = Import-CSV C:\Users\oj\Desktop\Test\hosts.csv
$scriptBlock = {
Remove-LocalUser -Name $args[0]
}
ForEach ($item in $hostdetail) {
$hostname = $($item.hostname)
$username = $($item.username)
$computer = $hostname
#Test network connection before making connection and Verify that the OS Version is 6.0 and above
If ((!(Test-Connection -comp $computer -count 1 -quiet)) -Or ((Get-WmiObject -ComputerName $computer Win32_OperatingSystem -ea stop).Version -lt 6.0)) {
Write-Warning "$computer is not accessible or The Operating System of the computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
}
else {
Invoke-Command -ComputerName $computer -ScriptBlock $scriptBlock -ArgumentList $username
}
}
推荐阅读
- swift - 如何预先缓冲 avplayer 项目?
- c# - C# 对字典进行排序
按值降序排列 - .net 2.0 中没有 Linq - json - 如何在 Delphi 7 中使用 DELETE 方法和 JSON 流源发送 Indy 请求?
- go - 如何在 Go 中定义用户自定义类型的常量值?
- javascript - 测试字符串是否包含字符串数组中的单词
- java - 我正在尝试对正在处理的图像进行马赛克效果,但图像保持不变?
- javascript - jQuery trigger() stopPropagation() 不工作 - 冒泡发生?
- amazon-web-services - AWS ELB/ALB http/2 通过 http/2(不是 http/1.1)传递给 EC2 实例
- javascript - 从对象获取值并推入数组javascript
- c# - .Net Core OAuth 嵌套声明未映射回用户