Pet*_*nce 25 windows powershell windows-service
我正在为 Windows 服务创建一个(本地)用户来运行。我有充分的理由不想使用 NETWORK SERVICE、LOCAL SERVICE 或 LOCAL SYSTEM。
我通过创建用户net user foobar "Abcd123!" /add- 这工作正常。
此时,c:\users\foobar不存在。
如果我创建用户的主目录,在用户登录(或更相关地)或用户所使用的服务启动之前,Windows 会创建一个名为的隔壁用户配置文件c:\users\foobar-{gibberish/SID/whatever}- 这不是一个可预测的名称。
我需要用户的主目录来包含诸如.ssh目录之类的东西,像这样的.gitconfig工具(不限于那些工具)假设它将是一个人使用它们,因此用户配置进入~/.... 通常,来自 Unix 遗产的工具。
那么 - 是否有一种编程方式(最好是 PowerShell 或开箱即用的命令行)来告诉 Windows 为本地用户创建用户配置文件?
我还没有尝试的事情:
C:\users\default(相当于/etc/skel),因为有几个不同的服务用户,一个尺寸不适合所有人。这也不会影响用户配置文件的创建时间,只会影响其中的内容。Swi*_*one 28
Windows 可以使用CreateProfile API按需创建用户配置文件
但是,如果不想创建可执行文件来执行此操作,则可以在 PowerShell 中调用 API。其他人已经做到了:github 上的示例。
代码的相关部分:
$methodName = 'UserEnvCP'
$script:nativeMethods = @();
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;
}
Run Code Online (Sandbox Code Playgroud)
Gre*_*kew 18
您需要做的就是以该用户身份运行命令,Windows 将创建配置文件:
psexec.exe -u foobar -p Abcd123! cmd.exe /c exit
https://docs.microsoft.com/en-us/sysinternals/downloads/psexec
| 归档时间: |
|
| 查看次数: |
7049 次 |
| 最近记录: |