[英]Simple Powershell questions (Creating a local ID and adding local administrator group plus some checks)
对 powershell 有点陌生,正在寻找一些指导。 我正在尝试创建一个简单的脚本来完成以下任务:
$serverlist = Get-Content C:\temp\servers.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"
}
}
}
PS,为简单起见仅使用通用凭据,之后将转换为最佳标准。 只是想获得更多编写 Powershell 的经验,以后可能会转换为自定义 function。
根据您的脚本,我注意到以下几点可以增强
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:\Windows\system32> 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
scope 修饰符来识别远程命令中的局部变量。
所以脚本可能是这样的:
$serverlist = Get-Content C:\temp\servers.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"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.