对powershell有点陌生,正在寻找一些指导。我正在尝试创建一个简单的脚本来完成以下任务:
- 检查服务器列表中是否已存在本地ID
- 如果没有,请创建一个并在服务器列表中添加到本地管理员组
- 注销结果
$serverlist = Get-Content C:tempservers.txt
$credential = Get-Credential
foreach ($server in $serverlist){
#User to search for
$USERNAME = "John"
#Declare LocalUser Object
$ObjLocalUser = $null
Invoke-Command -Credential $credential -Authentication Default -ComputerName $Server -ScriptBlock {
$ObjLocalUser = Get-LocalUser "John"
#Create the user if it was not found (Example)
if (!$ObjLocalUser) {
Write-Verbose "Creating User $($USERNAME)" #(Example)
NET USER "John" "Generic Password" /ADD /passwordchg:no
NET LOCALGROUP "Administrators" "Joe Doe" /ADD
}
else {
Write-Verbose "John" already exists"
}
}
}
p.S只是为了简单起见而使用通用证书,之后将转换为最佳标准。只是想获得更多编写Powershell的经验,稍后可能会转换为自定义函数。
根据您的脚本,我注意到以下几点可以增强
1-您不必使用for循环来遍历服务器列表,而是可以将服务器列表数组直接传递给Invoke-Command
的ComputerName
参数
get-help Invoke-Command
Invoke-Command [[-ComputerName] <string[]>]
# <string[]: indicate that the computername property accepts an array not string
所以在你的脚本中,你可以按照使用它
Invoke-Command -Credential $credential -Authentication Default -ComputerName $Serverlist {...}
2-在Invoke-Command
中,使用命令搜索用户是否存在
Get-LocalUser "John"
但如果用户不存在,这会给你一个错误
PS C:Windowssystem32> Get-LocalUser john
Get-LocalUser : User john was not found.
At line:1 char:1
+ Get-LocalUser john
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (john:String) [Get-LocalUser], UserNotFoundException
+ FullyQualifiedErrorId : UserNotFound,Microsoft.PowerShell.Commands.GetLocalUserCommand
相反,您可以使用搜索用户
Get-LocalUser | where {$_.name -eq $USERNAME})
3-您不需要使用变量$ObjLocalUser
,您可以使用if条件直接检查搜索结果,如下所示:
if (!(Get-LocalUser | where {$_.name -eq $USERNAME})) {
Write-output "Creating User $USERNAME"
} else {
Write-output "User: $USERNAME already exists"
}
最后:为了在invoke-commnd
中使用局部变量,您可以使用Using
作用域修饰符来标识远程命令中的局部变量。
所以脚本可能是这样的:
$serverlist = Get-Content C:tempservers.txt
$credential = Get-Credential
$USERNAME = "John"
Invoke-Command -Credential $credential -Authentication Default -ComputerName $serverlist -ScriptBlock {
#Create the user if it was not found (Example)
if (!(Get-LocalUser | where {$_.name -eq $Using:USERNAME})) {
Write-output "Creating User $Using:USERNAME"
NET USER $Using:USERNAME "Generic Password" /ADD /passwordchg:no
NET LOCALGROUP "Administrators" $Using:USERNAME /ADD
} else {
Write-output "User: $Using:USERNAME already exists"
}
}