我是一个创建本地用户并设置密码的脚本。
我检查了一些错误,以确保名称和密码不是空白。出于某种原因,即使用户名和密码不是空白,当它不为空或空时仍然表示它为NULL或空:
$Computername = $env:COMPUTERNAME
$ADSIComp = [adsi]"WinNT://$Computername"
$Username = 'TestProx'
$Username = Read-Host -Prompt 'Please enter the New User'
#check that Username is not empty
if([string]::IsNullOrEmpty($destDir))
{
Write-Host "Username is NULL or EMPTY"
}
else
{
$NewUser = $ADSIComp.Create('User',$Username)
#Create password
$Password = Read-Host -Prompt "Enter password for $Username" -AsSecureString
#check that password is not empty
if([string]::IsNullOrEmpty($destDir))
{
Write-Host "password is NULL or EMPTY"
}
else
{
$BSTR = [system.runtime.interopservices.marshal]::SecureStringToBSTR($Password)
$_password = [system.runtime.interopservices.marshal]::PtrToStringAuto($BSTR)
#Set password on account
$NewUser.SetPassword(($_password))
$NewUser.SetInfo()
}
}
答案 0 :(得分:2)
在第一个if
声明中,您必须检查$username
,并在$password
而不是$destDir
内检查{<1}}:
$Computername = $env:COMPUTERNAME
$ADSIComp = [adsi]"WinNT://$Computername"
$Username = 'TestProx'
$Username = Read-Host -Prompt 'Please enter the New User'
#check that Username is not empty
if([string]::IsNullOrEmpty($Username))
{
Write-Host "Username is NULL or EMPTY"
}
else
{
$NewUser = $ADSIComp.Create('User',$Username)
#Create password
$Password = Read-Host -Prompt "Enter password for $Username" -AsSecureString
#check that password is not empty
if([string]::IsNullOrEmpty($Password))
{
Write-Host "password is NULL or EMPTY"
}
else
{
$BSTR = [system.runtime.interopservices.marshal]::SecureStringToBSTR($Password)
$_password = [system.runtime.interopservices.marshal]::PtrToStringAuto($BSTR)
#Set password on account
$NewUser.SetPassword(($_password))
$NewUser.SetInfo()
}
}