我正在尝试删除主机名和用户名位于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
}
答案 0 :(得分:1)
在调用命令之前调用 $脚本块。您应该通过 -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
}
}