Advertisement
Guest User

unknown ps1

a guest
Dec 6th, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.53 KB | None | 0 0
  1. <#
  2. .DESCRIPTION
  3. This script performs network drive mappings with PowerShell and is auto generated by the intune-drive-mapping-generator (https://intunedrivemapping.azurewebsites.net).
  4. When executed under SYSTEM authority a scheduled task is created to ensure recurring script execution on each user logon.
  5.  
  6. .NOTES
  7. Author: Nicola Suter, nicolonsky tech: https://tech.nicolonsky.ch
  8. #>
  9.  
  10. [CmdletBinding()]
  11. Param()
  12.  
  13.  
  14. ###########################################################################################
  15. # Start transcript for logging #
  16. ###########################################################################################
  17.  
  18. Start-Transcript -Path $(Join-Path $env:temp "DriveMapping.log")
  19.  
  20. ###########################################################################################
  21. # Input values from generator #
  22. ###########################################################################################
  23.  
  24. $homed=""
  25. $omd=$env:OneDrive+"\My Documents"
  26. $od=$env:OneDrive+"\Documents"
  27. if ($env:homeshare)
  28. {
  29. $homed="\\\\mbs-azserver01\\home$\\$env:HOMESHARE"
  30. } elseif ($env:OneDrive)
  31. {
  32. $homed=$env:OneDrive.Replace(":", "$")
  33. if (Test-Path -Path $od)
  34. {
  35. $homed=$homed+"\Documents"
  36. } elseif (Test-Path -Path $omd)
  37. {
  38. $homed=$homed+"\My Documents"
  39. }
  40. }
  41.  
  42.  
  43. $driveMappingJson='[
  44. {"Path":"\\\\mbs-azserver01\\files2\\Data","DriveLetter":"U","Label":"Data.","Id":0,"GroupFilter":null},
  45. {"Path":"\\\\mbs-azserver01\\files\\publications","DriveLetter":"P","Label":"Publications.","Id":2,"GroupFilter":null},
  46. {"Path":"\\\\mbs-azserver01\\files\\Site Data","DriveLetter":"V","Label":"Site Data.","Id":3,"GroupFilter":null},
  47. {"Path":"\\\\mbs-azserver01\\files2\\MBM-LA","DriveLetter":"K","Label":"MBM LA Files.","Id":4,"GroupFilter":null},
  48. {"Path":"\\\\mbs-azserver01\\files2\\sundata","DriveLetter":"S","Label":"Sunwheel Data.","Id":5,"GroupFilter":null},
  49. {"Path":"\\\\mbs-azserver01\\files2\\MBS-LA","DriveLetter":"G","Label":"MBS LA Files.","Id":6,"GroupFilter":null},
  50. {"Path":"\\\\mbs-azserver01\\files\\urban","DriveLetter":"X","Label":"Urban Files.","Id":8,"GroupFilter":null},
  51. {"Path":"\\\\$env:computername\\$homed","DriveLetter":"Z","Label":"My Documents.","Id":10,"GroupFilter":null},
  52. {"Path":"\\\\mbs-azserver01\\files2\\Data\\Projects","DriveLetter":"F","Label":"Project Files.","Id":11,"GroupFilter":null}
  53. ]'
  54.  
  55. $driveMappingConfig= $driveMappingJson | ConvertFrom-Json
  56.  
  57. Start-Sleep -Seconds 30
  58.  
  59. ###########################################################################################
  60. # Helper function to determine a users group membership #
  61. ###########################################################################################
  62.  
  63. # Kudos for Tobias Renström who showed me this!
  64. function Get-ADGroupMembership {
  65. param(
  66. [parameter(Mandatory=$true)]
  67. [string]$UserPrincipalName
  68. )
  69. process{
  70.  
  71. try{
  72.  
  73. $Searcher = New-Object -TypeName System.DirectoryServices.DirectorySearcher
  74. $Searcher.Filter = "(&(userprincipalname=$UserPrincipalName))"
  75. $Searcher.SearchRoot = "LDAP://$env:USERDNSDOMAIN"
  76. $DistinguishedName = $Searcher.FindOne().Properties.distinguishedname
  77. $Searcher.Filter = "(member:1.2.840.113556.1.4.1941:=$DistinguishedName)"
  78.  
  79. [void]$Searcher.PropertiesToLoad.Add("name")
  80.  
  81. $List = [System.Collections.Generic.List[String]]@()
  82.  
  83. $Results = $Searcher.FindAll()
  84.  
  85. foreach ($Result in $Results) {
  86. $ResultItem = $Result.Properties
  87. [void]$List.add($ResultItem.name)
  88. }
  89.  
  90. $List
  91.  
  92. }catch{
  93. #Nothing we can do
  94. Write-Warning $_.Exception.Message
  95. }
  96. }
  97. }
  98.  
  99. ###########################################################################################
  100. # Get current group membership for the group filter capabilities #
  101. ###########################################################################################
  102.  
  103. if ($driveMappingConfig.GroupFilter){
  104. try{
  105. #check if running as user and not system
  106. if (-not ($(whoami -user) -match "S-1-5-18")){
  107.  
  108. $groupMemberships = Get-ADGroupMembership -UserPrincipalName $(whoami -upn)
  109. }
  110. }catch{
  111. #nothing we can do
  112. }
  113. }
  114. ###########################################################################################
  115. # Mapping network drives #
  116. ###########################################################################################
  117. #Get PowerShell drives and rename properties
  118. try{
  119.  
  120. $psDrives = Get-PSDrive | Select-Object @{N="DriveLetter"; E={$_.Name}}, @{N="Path"; E={$_.DisplayRoot}}
  121.  
  122. }catch{
  123.  
  124. Write-Warning $_.Exception.Message
  125. }
  126.  
  127. #iterate through all network drive configuration entries
  128. $driveMappingConfig.GetEnumerator() | ForEach-Object {
  129.  
  130. try{
  131.  
  132. #check if variable in unc path exists, e.g. for $env:USERNAME
  133. if ($PSItem.Path -match '\$env:'){
  134.  
  135. $PsItem.Path=$ExecutionContext.InvokeCommand.ExpandString($PSItem.Path)
  136.  
  137. }
  138.  
  139. #if label is null we need to set it to empty in order to avoid error
  140. if ($PSItem.Label -eq $null){
  141.  
  142. $Psitem.Label = ""
  143. }
  144.  
  145. #check if the drive is already connected with an identical configuration
  146. if ( -not ($psDrives.Path -contains $PSItem.Path -and $psDrives.DriveLetter -contains $PSItem.DriveLetter)){
  147.  
  148. #check if drive exists - but with wrong config - to delete it
  149. if($psDrives.Path -contains $PSItem.Path -or $psDrives.DriveLetter -contains $PSItem.DriveLetter){
  150.  
  151. Get-PSDrive | Where-Object {$_.DisplayRoot -eq $PSItem.Path -or $_.Name -eq $PSItem.DriveLetter} | Remove-PSDrive -ErrorAction SilentlyContinue
  152. }
  153.  
  154. ## check itemleveltargeting for group membership
  155. if ($PSItem.GroupFilter -ne $null -and $groupMemberships -contains $PSItem.GroupFilter){
  156.  
  157. Write-Output "Mapping network drive $($PSItem.Path)"
  158.  
  159. $null = New-PSDrive -PSProvider FileSystem -Name $PSItem.DriveLetter -Root $PSItem.Path -Description $PSItem.Label -Persist -Scope global -EA SilentlyContinue
  160.  
  161. (New-Object -ComObject Shell.Application).NameSpace("$($PSItem.DriveLetter):").Self.Name=$PSItem.Label
  162.  
  163. }elseif ($PSItem.GroupFilter -eq $null) {
  164.  
  165. Write-Output "Mapping network drive $($PSItem.Path)"
  166.  
  167. $null = New-PSDrive -PSProvider FileSystem -Name $PSItem.DriveLetter -Root $PSItem.Path -Description $PSItem.Label -Persist -Scope global -EA SilentlyContinue
  168.  
  169. (New-Object -ComObject Shell.Application).NameSpace("$($PSItem.DriveLetter):").Self.Name=$PSItem.Label
  170. }
  171. }else{
  172.  
  173. Write-Output "Drive already exists with same DriveLetter and Path"
  174. }
  175. }catch{
  176.  
  177. Write-Warning $_.Exception.Message
  178. }
  179. }
  180. ###########################################################################################
  181. # End & finish transcript #
  182. ###########################################################################################
  183.  
  184. Stop-transcript
  185.  
  186. ###########################################################################################
  187. # Done #
  188. ###########################################################################################
  189.  
  190. #!SCHTASKCOMESHERE!#
  191.  
  192. ###########################################################################################
  193. # If this script is running under system (IME) scheduled task is created (recurring) #
  194. ###########################################################################################
  195.  
  196. Start-Transcript -Path $(Join-Path -Path $env:temp -ChildPath "IntuneDriveMappingScheduledTask.log")
  197.  
  198. if ($(whoami -user) -match "S-1-5-18"){
  199.  
  200. Write-Output "Running as System --> creating scheduled task which will run on user logon"
  201.  
  202. ###########################################################################################
  203. # Get the current script path and content and save it to the client #
  204. ###########################################################################################
  205.  
  206. $currentScript= Get-Content -Path $($PSCommandPath)
  207.  
  208. $schtaskScript=$currentScript[(0) .. ($currentScript.IndexOf("#!SCHTASKCOMESHERE!#") -1)]
  209.  
  210. $scriptSavePath=$(Join-Path -Path $env:ProgramData -ChildPath "intune-drive-mapping-generator")
  211.  
  212. if (-not (Test-Path $scriptSavePath)){
  213.  
  214. New-Item -ItemType Directory -Path $scriptSavePath -Force
  215. }
  216.  
  217. $scriptSavePathName="DriveMappping.ps1"
  218.  
  219. $scriptPath= $(Join-Path -Path $scriptSavePath -ChildPath $scriptSavePathName)
  220.  
  221. $schtaskScript | Out-File -FilePath $scriptPath -Force
  222.  
  223. ###########################################################################################
  224. # Create dummy vbscript to hide PowerShell Window popping up at logon #
  225. ###########################################################################################
  226.  
  227. $vbsDummyScript = "
  228. Dim shell,fso,file
  229.  
  230. Set shell=CreateObject(`"WScript.Shell`")
  231. Set fso=CreateObject(`"Scripting.FileSystemObject`")
  232.  
  233. strPath=WScript.Arguments.Item(0)
  234.  
  235. If fso.FileExists(strPath) Then
  236. set file=fso.GetFile(strPath)
  237. strCMD=`"powershell -nologo -executionpolicy ByPass -command `" & Chr(34) & `"&{`" &_
  238. file.ShortPath & `"}`" & Chr(34)
  239. shell.Run strCMD,0
  240. End If
  241. "
  242.  
  243. $scriptSavePathName="IntuneDriveMapping-VBSHelper.vbs"
  244.  
  245. $dummyScriptPath= $(Join-Path -Path $scriptSavePath -ChildPath $scriptSavePathName)
  246.  
  247. $vbsDummyScript | Out-File -FilePath $dummyScriptPath -Force
  248.  
  249. $wscriptPath = Join-Path $env:SystemRoot -ChildPath "System32\wscript.exe"
  250.  
  251. ###########################################################################################
  252. # Register a scheduled task to run for all users and execute the script on logon #
  253. ###########################################################################################
  254.  
  255. $schtaskName= "IntuneDriveMapping"
  256. $schtaskDescription="Map network drives from intune-drive-mapping-generator."
  257.  
  258. $trigger = New-ScheduledTaskTrigger -AtLogOn
  259. #Execute task in users context
  260. $principal= New-ScheduledTaskPrincipal -GroupId "S-1-5-32-545" -Id "Author"
  261. #call the vbscript helper and pass the PosH script as argument
  262. $action = New-ScheduledTaskAction -Execute $wscriptPath -Argument "`"$dummyScriptPath`" `"$scriptPath`""
  263. $settings= New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
  264.  
  265. $null=Register-ScheduledTask -TaskName $schtaskName -Trigger $trigger -Action $action -Principal $principal -Settings $settings -Description $schtaskDescription -Force
  266.  
  267. Start-ScheduledTask -TaskName $schtaskName
  268. }
  269.  
  270. Stop-Transcript
  271.  
  272. ###########################################################################################
  273. # Done #
  274. ###########################################################################################
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement