Skip to content

Instantly share code, notes, and snippets.

@jkbryan
Created October 2, 2018 21:05
Show Gist options
  • Save jkbryan/ab13139e830f634812be95d67702ad2e to your computer and use it in GitHub Desktop.
Save jkbryan/ab13139e830f634812be95d67702ad2e to your computer and use it in GitHub Desktop.
create-credential.ps1
#CredMan stuff
$sig = @"
[DllImport("Advapi32.dll", SetLastError=true, EntryPoint="CredWriteW", CharSet=CharSet.Unicode)]
public static extern bool CredWrite([In] ref Credential userCredential, [In] UInt32 flags);
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct Credential
{
public UInt32 flags;
public UInt32 type;
public IntPtr targetName;
public IntPtr comment;
public System.Runtime.InteropServices.ComTypes.FILETIME lastWritten;
public UInt32 credentialBlobSize;
public IntPtr credentialBlob;
public UInt32 persist;
public UInt32 attributeCount;
public IntPtr Attributes;
public IntPtr targetAlias;
public IntPtr userName;
}
"@
Add-Type -MemberDefinition $sig -Namespace "ADVAPI32" -Name 'Util'
$cred = New-Object ADVAPI32.Util+Credential
$cred.flags = 0
$cred.type = 1
#Get MSOL creds
While (!$UserName) {$UserName = (Read-Host "`n MSOL username (user`@domain)").ToUpper()}
#Set the name of the CredMan credentials
$TargetName = "LicenceManagment"
$cred.targetName = [System.Runtime.InteropServices.Marshal]::StringToCoTaskMemUni($TargetName)
$cred.userName = [System.Runtime.InteropServices.Marshal]::StringToCoTaskMemUni($UserName)
$cred.attributeCount = 0
$cred.persist = 2
While (!$Password) {$Password = Read-Host -assecurestring "`n MSOL password"}
$objCreds = New-Object Management.Automation.PSCredential $UserName, $Password
$Password = $objCreds.GetNetworkCredential().Password
#Validating MSOL creds
Write-Host "`n Validating MSOL credentials"
Import-Module MSOnline
Connect-MsolService -Credential $objCreds
If ($?)
{
Write-Host "`n`tSuccess" -ForegroundColor Green
}
Else
{
Write-Host "`n`tFailed MSOL credential validation. Exiting...`n" -ForegroundColor Red
Exit
}
$cred.credentialBlobSize = [System.Text.Encoding]::Unicode.GetBytes($Password).length
$cred.credentialBlob = [System.Runtime.InteropServices.Marshal]::StringToCoTaskMemUni($Password)
#Store the MSOL creds in CredMan
$CredWrite = [ADVAPI32.Util]::CredWrite([ref]$cred,0)
If ($CredWrite)
{
Write-Host "`n`tAdded MSOL credentials to the local Credential Manager" -ForegroundColor Green
}
Else
{
Write-Host "`n`tFailed adding MSOL credentials to the local Credential Manager. Exiting...`n" -ForegroundColor Red
Exit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment