Last active
October 25, 2022 14:32
-
-
Save PanosGreg/8346c58741cbc19c99179b16403a0267 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function New-UserProfile { | |
<# | |
.EXAMPLE | |
New-UserProfile -DomainName MyLab -UserName MyUser -Verbose | |
#> | |
[cmdletbinding()] | |
[OutputType([System.IO.DirectoryInfo])] | |
param( | |
[Parameter(Mandatory=$true)] | |
[String]$UserName, | |
[String]$DomainName = $env:USERDOMAIN | |
) | |
$PSDefaultParameterValues = @{'Get-CimInstance:Verbose' = $false} | |
try { | |
Write-Verbose "Look up SID for user $UserName..." | |
$objUser = [Security.Principal.NTAccount]::new($DomainName, $UserName) | |
$strSID = $objUser.Translate([Security.Principal.SecurityIdentifier]) | |
$SID = $strSID.Value | |
} | |
catch {Write-Warning "Could not find SID for $UserName" ; throw $_} | |
$code = @' | |
using System; | |
using System.Runtime.InteropServices; | |
public static class PInvoke { | |
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)] | |
public static extern int CreateProfile( [MarshalAs(UnmanagedType.LPWStr)] String pszUserSid, [MarshalAs(UnmanagedType.LPWStr)] String pszUserName, [Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszProfilePath, uint cchProfilePath); | |
} | |
'@ | |
$sb = [System.Text.StringBuilder]::new(260) | |
$len = $sb.Capacity | |
try {Add-Type -TypeDefinition $code -ErrorAction Stop} | |
catch {Write-Warning 'Could not load pinvoke method' ; throw $_} | |
Write-Verbose "Create profile for user $UserName..." | |
try {$result = [PInvoke]::CreateProfile($SID, $UserName, $sb, $len)} | |
catch {throw $_.Exception.Message} | |
switch($result) { | |
'-2147024713' {Write-Warning "Profile already exists for $userName" ; break} | |
'-2147024809' {Write-Warning "$username not found" ; break} | |
'-2147023582' {Write-Warning 'Please run this elevated' ; return} | |
0 {Write-Verbose "Profile created for user $UserName" ; break} | |
default {Write-Warning 'Unknown result' ; break} | |
} | |
if ($result -eq 0 -or $result -eq '-2147024713') { | |
Write-Verbose "Find the profile path for $UserName..." | |
$Path = (Get-CimInstance Win32_UserProfile | where SID -eq $SID).LocalPath | |
if (Test-Path $Path) {Get-Item $Path} # <-- this is the output, should be [System.IO.DirectoryInfo] | |
else {throw "Could not find profile $Path"} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment