intuneServerShareMapper.ps1 6.56 KB
Newer Older
1 2 3 4 5 6 7
#Author:           Jos Lieben (OGD)
#Author Company:   OGD (http://www.ogd.nl)
#Author Blog:      http://www.lieben.nu
#Date:             05-06-2018
#Purpose:          Configurable drivemapping to server shares with automatic querying for credentials

#REQUIRED CONFIGURATION
8 9 10
$driveLetter = "I" #change to desired driveletter (don't use double colon : )
$path = '\\nlfs01\Afdelingen' #change to desired server / share path
$shortCutTitle = "I-Drive" #this will be the name of the shortcut
11
$autosuggestLogin = $True #automatically prefills the login field of the auth popup with the user's O365 email (azure ad join)
12 13 14
$desiredShortcutLocation = [Environment]::GetFolderPath("Desktop") #you can also use MyDocuments or any other valid input for the GetFolderPath function

###START SCRIPT
15 16 17 18 19 20 21 22 23 24 25 26 27

$desiredMapScriptFolder = Join-Path $Env:LOCALAPPDATA -ChildPath "Lieben.nu"
$desiredMapScriptPath = Join-Path $desiredMapScriptFolder -ChildPath "SMBdriveMapper.ps1"

if(![System.IO.Directory]::($desiredMapScriptFolder)){
    New-Item -Path $desiredMapScriptFolder -Type Directory -Force
}

$scriptContent = "
Param(
    `$driveLetter,
    `$sourcePath
)
28

29 30
`$driveLetter = `$driveLetter.SubString(0,1)

31 32 33
`$desiredMapScriptFolder = Join-Path `$Env:LOCALAPPDATA -ChildPath `"Lieben.nu`"

Start-Transcript -Path (Join-Path `$desiredMapScriptFolder -ChildPath `"SMBdriveMapper.log`") -Force
34 35
"
if($autosuggestLogin){
36 37 38 39 40 41 42 43 44
    $scriptContent+= "
try{
    `$objUser = New-Object System.Security.Principal.NTAccount(`$Env:USERNAME)
    `$strSID = (`$objUser.Translate([System.Security.Principal.SecurityIdentifier])).Value
    `$basePath = `"HKLM:\SOFTWARE\Microsoft\IdentityStore\Cache\`$strSID\IdentityCache\`$strSID`"
    if((test-path `$basePath) -eq `$False){
        `$userId = `$Null
    }
    `$userId = (Get-ItemProperty -Path `$basePath -Name UserName).UserName
45
    Write-Output `"Detected user id: `$userId`"
46
}catch{
47
    Write-Output `"Failed to auto detect user id, will query`" 
48 49 50
    `$Null
}
"
51
}else{
52 53 54
    $scriptContent+= "
`$userId = `$null
    "
55 56
}

57
$scriptContent+= "
58
`$serverPath = `"`$(([URI]`$sourcePath).Host)`"
59 60 61
#check if other mappings share the same path, in that case we shouldn't need credentials
`$authRequired = `$true
try{
62
     `$count = @(get-psdrive -PSProvider filesystem | where-object {`$_.DisplayRoot -and `$_.DisplayRoot.Replace('\','').StartsWith(`$serverPath)}).Count
63 64 65 66 67 68 69
}catch{`$Null}

if(`$count -gt 0){
    Write-Output `"A drivemapping to this server already exists, so authentication should not be required`"
    `$authRequired = `$False
}

70 71 72
[void] [System.Reflection.Assembly]::LoadWithPartialName(`"System.Drawing`") 
[void] [System.Reflection.Assembly]::LoadWithPartialName(`"System.Windows.Forms`")

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
if(`$authRequired){
    `$form = New-Object System.Windows.Forms.Form
    `$form.Text = `"Connect to `$driveLetter drive`"
    `$form.Size = New-Object System.Drawing.Size(300,200)
    `$form.StartPosition = 'CenterScreen'
    `$form.MinimizeBox = `$False
    `$form.MaximizeBox = `$False

    `$OKButton = New-Object System.Windows.Forms.Button
    `$OKButton.Location = New-Object System.Drawing.Point(75,120)
    `$OKButton.Size = New-Object System.Drawing.Size(75,23)
    `$OKButton.Text = 'OK'
    `$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    `$form.AcceptButton = `$OKButton
    `$form.Controls.Add(`$OKButton)

    `$CancelButton = New-Object System.Windows.Forms.Button
    `$CancelButton.Location = New-Object System.Drawing.Point(150,120)
    `$CancelButton.Size = New-Object System.Drawing.Size(75,23)
    `$CancelButton.Text = 'Cancel'
    `$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    `$form.CancelButton = `$CancelButton
    `$form.Controls.Add(`$CancelButton)

    `$label = New-Object System.Windows.Forms.Label
    `$label.Location = New-Object System.Drawing.Point(10,20)
    `$label.Size = New-Object System.Drawing.Size(280,20)
    `$label.Text = `"Username for `$driveLetter drive`"
    `$form.Controls.Add(`$label)

    `$textBox = New-Object System.Windows.Forms.TextBox
    `$textBox.Location = New-Object System.Drawing.Point(10,40)
    `$textBox.Size = New-Object System.Drawing.Size(260,20)
    `$textBox.Text = `$userId
    `$form.Controls.Add(`$textBox)

    `$label2 = New-Object System.Windows.Forms.Label
    `$label2.Location = New-Object System.Drawing.Point(10,60)
    `$label2.Size = New-Object System.Drawing.Size(280,20)
    `$label2.Text = 'Password:'
    `$form.Controls.Add(`$label2)

    `$textBox2 = New-Object System.Windows.Forms.MaskedTextBox
    `$textBox2.PasswordChar = '*'
    `$textBox2.Location = New-Object System.Drawing.Point(10,80)
    `$textBox2.Size = New-Object System.Drawing.Size(260,20)
    `$form.Controls.Add(`$textBox2)

    `$form.Topmost = `$true

    `$form.Add_Shown({`$textBox.Select()})
    `$result = `$form.ShowDialog()

    if (`$result -eq [System.Windows.Forms.DialogResult]::OK -and `$textBox2.Text.Length -gt 5 -and `$textBox.Text.Length -gt 4)
    {
        `$secpasswd = ConvertTo-SecureString `$textBox2.Text -AsPlainText -Force
        `$credentials = New-Object System.Management.Automation.PSCredential (`$textBox.Text, `$secpasswd)
    }else{
        `$OUTPUT= [System.Windows.Forms.MessageBox]::Show(`"`$driveLetter will not be available, as you did not enter credentials`", `"`$driveLetter error`" , 0) 
        Stop-Transcript
        Exit
    }
}
136
try{`Remove-PSDrive -Name `$driveLetter -Force}catch{`$Null}
137 138

try{
139 140 141 142 143
    if(`$authRequired){
        New-PSDrive -Name `$driveLetter -PSProvider FileSystem -Root `$sourcePath -Credential `$credentials -Persist -ErrorAction Stop
    }else{
        Throw
    }
144
}catch{
145 146 147 148 149
    try{
        New-PSDrive -Name `$driveLetter -PSProvider FileSystem -Root `$sourcePath -Persist -ErrorAction Stop
    }catch{
         `$OUTPUT= [System.Windows.Forms.MessageBox]::Show(`"Connection failed, technical reason: `$(`$Error[0])`", `"`$driveLetter error`" , 0) 
    }
150 151 152
}
Stop-Transcript
"
153

154
$scriptContent | Out-File $desiredMapScriptPath -Force
155

156
$driveLetter = $driveLetter.SubString(0,1)
157 158
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut((Join-Path $desiredShortcutLocation -ChildPath "$($shortCutTitle).lnk"))
159 160
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.WorkingDirectory = "%SystemRoot%\WindowsPowerShell\v1.0\"
161
$Shortcut.Arguments =  "-WindowStyle Hidden -ExecutionPolicy ByPass -File `"$desiredMapScriptPath`" $driveLetter `"$path`""
162 163
$Shortcut.IconLocation = "explorer.exe ,0"
$shortcut.WindowStyle = 7
164
$Shortcut.Save()