【问题标题】:How to initialize new user account from command line如何从命令行初始化新用户帐户
【发布时间】:2020-06-12 11:09:06
【问题描述】:

我想在 Windows 10 上初始化新用户帐户,而无需从管理员登录并再次登录用户。现在我使用以下命令创建新帐户:

网络用户“用户名”“密码”/添加

接下来我运行一些带有加载用户配置文件的命令的程序:

C:> runas /profile /user:user program.exe

但是,它不等同于以该用户身份登录。环境和一些文件夹结构在没有实际登录的情况下没有准备好。有什么办法吗?

【问题讨论】:

  • 这是错误的论坛。属于超级用户

标签: command-line windows-10 user-accounts


【解决方案1】:

以用户身份运行程序应该足以创建配置文件。
但如果不是,这里有一个用于创建新配置文件的 Powershell 脚本:
https://gist.github.com/pjh/9753cd14400f4e3d4567f4553ba75f1d

<#
.Synopsis
   Rough PS functions to create new user profiles
.DESCRIPTION
   Call the Create-NewProfile function directly to create a new profile
.EXAMPLE
   Create-NewProfile -Username 'testUser1' -Password 'testUser1'
.NOTES
   Created by: Josh Rickard (@MS_dministrator) and Thom Schumacher (@driberif)
   Date: 24MAR2017
   Location: https://gist.github.com/crshnbrn66/7e81bf20408c05ddb2b4fdf4498477d8

   Contact: https://github.com/MSAdministrator
            MSAdministrator.com
            https://github.com/crshnbrn66
            powershellposse.com
#>


#Function to create the new local user first
function New-LocalUser
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $userName,
        # Param2 help description
        [string]
        $password
    )

    $system = [ADSI]"WinNT://$env:COMPUTERNAME";
    $user = $system.Create("user",$userName);
    $user.SetPassword($password);
    $user.SetInfo();

    $flag=$user.UserFlags.value -bor 0x10000;
    $user.put("userflags",$flag);
    $user.SetInfo();

    $group = [ADSI]("WinNT://$env:COMPUTERNAME/Users");
    $group.PSBase.Invoke("Add", $user.PSBase.Path);
}

#function to register a native method
function Register-NativeMethod
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$dll,

        # Param2 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]
        $methodSignature
    )

    $script:nativeMethods += [PSCustomObject]@{ Dll = $dll; Signature = $methodSignature; }
}
function Get-Win32LastError
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param($typeName = 'LastError')
 if (-not ([System.Management.Automation.PSTypeName]$typeName).Type)
    {
    $lasterrorCode = $script:lasterror | ForEach-Object{
        '[DllImport("kernel32.dll", SetLastError = true)]
         public static extern uint GetLastError();'
    }
        Add-Type @"
        using System;
        using System.Text;
        using System.Runtime.InteropServices;
        public static class $typeName {
            $lasterrorCode
        }
"@
    }
}
#function to add native method
function Add-NativeMethods
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param($typeName = 'NativeMethods')

    $nativeMethodsCode = $script:nativeMethods | ForEach-Object { "
        [DllImport(`"$($_.Dll)`")]
        public static extern $($_.Signature);
    " }

    Add-Type @"
        using System;
        using System.Text;
        using System.Runtime.InteropServices;
        public static class $typeName {
            $nativeMethodsCode
        }
"@
}

#Main function to create the new user profile
function Create-NewProfile {

    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$UserName,

        # Param2 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [string]
        $Password
    )

    Write-Verbose "Creating local user $Username";

    try
    {
        New-LocalUser -username $UserName -password $Password;
    }
    catch
    {
        Write-Error $_.Exception.Message;
        break;
    }
    $methodName = 'UserEnvCP'
    $script:nativeMethods = @();

    if (-not ([System.Management.Automation.PSTypeName]$MethodName).Type)
    {
        Register-NativeMethod "userenv.dll" "int CreateProfile([MarshalAs(UnmanagedType.LPWStr)] string pszUserSid,`
         [MarshalAs(UnmanagedType.LPWStr)] string pszUserName,`
         [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath)";

        Add-NativeMethods -typeName $MethodName;
    }

    $localUser = New-Object System.Security.Principal.NTAccount("$UserName");
    $userSID = $localUser.Translate([System.Security.Principal.SecurityIdentifier]);
    $sb = new-object System.Text.StringBuilder(260);
    $pathLen = $sb.Capacity;

    Write-Verbose "Creating user profile for $Username";

    try
    {
        [UserEnvCP]::CreateProfile($userSID.Value, $Username, $sb, $pathLen) | Out-Null;
    }
    catch
    {
        Write-Error $_.Exception.Message;
        break;
    }
}

function New-ProfileFromSID {

    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$UserName,
        [string]$domain = 'PHCORP'
    )
    $methodname = 'UserEnvCP2'
    $script:nativeMethods = @();

    if (-not ([System.Management.Automation.PSTypeName]$methodname).Type)
    {
        Register-NativeMethod "userenv.dll" "int CreateProfile([MarshalAs(UnmanagedType.LPWStr)] string pszUserSid,`
         [MarshalAs(UnmanagedType.LPWStr)] string pszUserName,`
         [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath)";

        Add-NativeMethods -typeName $methodname;
    }

    $sb = new-object System.Text.StringBuilder(260);
    $pathLen = $sb.Capacity;

    Write-Verbose "Creating user profile for $Username";
    #$SID= ((get-aduser -id $UserName -ErrorAction Stop).sid.value)
  if($domain)
   {
        $objUser = New-Object System.Security.Principal.NTAccount($domain, $UserName)
        $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
        $SID = $strSID.Value
   }
   else 
   {
       $objUser = New-Object System.Security.Principal.NTAccount($UserName)
       $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
       $SID = $strSID.Value
   }
    Write-Verbose "$UserName SID: $SID"
    try
    {
       $result = [UserEnvCP2]::CreateProfile($SID, $Username, $sb, $pathLen) 
       if($result -eq '-2147024713')
       {
           $status = "$userName already exists"
           write-verbose "$username Creation Result: $result"
        }
        elseif($result -eq '-2147024809')
        {
            $staus = "$username Not Found"
            write-verbose "$username creation result: $result"
        }
       elseif($result -eq 0)
       {
           $status = "$username Profile has been created"
           write-verbose "$username Creation Result: $result"
       }
       else
       {
          $status = "$UserName unknown return result: $result"
       }
    }
    catch
    {
        Write-Error $_.Exception.Message;
        break;
    }
    $status
}
Function Remove-Profile {

    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]$UserName,
        [string]$ProfilePath,
        [string]$domain = 'PHCORP'
    )
    $methodname = 'userenvDP'
    $script:nativeMethods = @();

    if (-not ([System.Management.Automation.PSTypeName]"$methodname.profile").Type)
    {
      add-type @"
using System.Runtime.InteropServices;

namespace $typename
{
    public static class UserEnv
    {
        [DllImport("userenv.dll", CharSet = CharSet.Unicode, ExactSpelling = false, SetLastError = true)]
        public static extern bool DeleteProfile(string sidString, string profilePath, string computerName);

        [DllImport("kernel32.dll")]
        public static extern uint GetLastError();
    }

    public static class Profile
    {
        public static uint Delete(string sidString)
        { //Profile path and computer name are optional
            if (!UserEnv.DeleteProfile(sidString, null, null))
            {
                return UserEnv.GetLastError();
            }

            return 0;
        }
    }
}
"@
    }

   #$SID= ((get-aduser -id $UserName -ErrorAction Stop).sid.value)
   if($domain)
   {
        $objUser = New-Object System.Security.Principal.NTAccount($domain, $UserName)
        $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
        $SID = $strSID.Value
   }
   else 
   {
       $objUser = New-Object System.Security.Principal.NTAccount($UserName)
       $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
       $SID = $strSID.Value
   }
    Write-Verbose "$UserName SID: $SID"
    try
    {
        #http://stackoverflow.com/questions/31949002/c-sharp-delete-user-profile
       $result = [userenvDP.Profile]::Delete($SID)
    }
    catch
    {
        Write-Error $_.Exception.Message;
        break;
    }
    $LastError
}

Export-ModuleMember Create-NewProfile

【讨论】:

    【解决方案2】:
    net users /add name password
    

    并将其添加到管理员使用

    net localgroup administrators /add name
    

    例如,添加用户test,密码为123456789

    net users /add test 123456789
    

    并将test 添加到管理员

    net localgroup administrators /add test
    

    请注意,这必须在管理员 cmd 中运行并创建 本地 帐户。

    如需更多帮助,请在 cmd 中运行 net users /?help net users

    要在 powershell 中执行此操作,您也可以这样做:

    New-LocalUser -Name "Name" -Password "Password" -AccountNeverExpires -FullName "NameName"
    

    这将创建一个不会过期的新用户帐户,其名称为 Name 密码 Password 和全名(文件资源管理器的内容和缩写)NameName。还需要管理员。

    这些示例将初始化新用户,如您在 powershell 或 cmd 中再次检查 net users 所见。这些也将创建新的用户目录。

    您的问题是您试图启动程序作为该用户的环境,该程序尚未设置为该用户只需使用即可运行

    runas /env /profile /user:user program.exe
    

    加上/env开关

    runas /?

    /env              to use current environment instead of user's.
    

    如果我用

    创建用户test
    net users /add test 123456789
    

    您可以看到它们将出现在net users 查询和net localgroup users 查询的结果中。您还将看到他们的用户文件夹已被初始化

    cd %homepath%\..
    dir
     Volume in drive C is Local Disk
     Volume Serial Number is 1234-ABCD
    
     Directory of C:\Users
    
    06/20/2020  10:05 PM    <DIR>          .
    06/20/2020  10:05 PM    <DIR>          ..
    06/18/2020  01:15 PM    <DIR>          Neko
    03/14/2020  09:16 PM    <DIR>          Public
    06/20/2020  10:05 PM    <DIR>          test
    

    必须在该用户中运行某些东西才能真正初始化。

    在 powershell 中查看 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/new-localuser?view=powershell-5.1https://ss64.com/nt/net-useradmin.htmlget-help New-LocalUser -full,在 cmd 中查看 net user /?runas /?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-23
      • 2015-10-18
      • 2013-07-31
      • 2015-07-01
      • 2022-07-31
      • 2019-01-12
      • 2013-06-01
      • 2021-03-30
      相关资源
      最近更新 更多