2017-04-10 115 views
1

我是一个脚本,将创建一个本地用户,并设置密码。用户名和密码返回null或空

我把一些错误检查,以确保用户名和密码是不为空。出于某种原因,即使用户名和密码不为空它仍然说,不为空或空当它是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() 
    } 
} 

回答

2

在您需要检查$username,第二个用于内第一if声明$password而不是$destDir

$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() 
    } 
} 
相关问题