My very first PowerShell script

What is this?

This script is a little program I did to make easier the Service Desk days, as I can edit the loginScript of the users and add or delete entries without connecting servers. Does not matters if they call for a printer or whatever.

It can also create a network share, for individual use, with minimun priviledges on NTFS and SMB acls.

How to use this?

It has been written to work in my environment, but with few changes can be adapted for almost every other domain.

Just look for the "$Domain" tag and change this with yours, or you can add a textbox to switch between forests, if needed.

Other thing is that users name their scripts with their username, so the username and the login script path will have a string in common.

This just work for me, hope will be useful for you!

This script:

Add-Type -AssemblyName PresentationFramework

# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

function Test-Cred {

## From www.powershellbros.com

    [CmdletBinding()]
    [OutputType([String])] 
       
    Param ( 
        [Parameter( 
            Mandatory = $false, 
            ValueFromPipeLine = $true, 
            ValueFromPipelineByPropertyName = $true
        )] 
        [Alias( 
            'PSCredential'
        )] 
        [ValidateNotNull()] 
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()] 
        $Credentials
    )
    $Domain = $null
    $Root = $null
    $Username = $null
    $Password = $null
      
    If($Credentials -eq $null)
    {
        Try
        {
            $Credentials = Get-Credential "domain\$env:username" -ErrorAction Stop
        }
        Catch
        {
            $ErrorMsg = $_.Exception.Message
            Write-Warning "Failed to validate credentials: $ErrorMsg "
            Pause
            Break
        }
    }
      
    # Checking module
    Try
    {
        # Split username and password
        $Username = $credentials.username
        $Password = $credentials.GetNetworkCredential().password
  
        # Get Domain
        $Root = "LDAP://" + ([ADSI]'').distinguishedName
        $Domain = New-Object System.DirectoryServices.DirectoryEntry($Root,$UserName,$Password)
    }
    Catch
    {
        $_.Exception.Message
        Continue
    }
  
    If(!$domain)
    {
        Write-Warning "Something went wrong"
    }
    Else
    {
        If ($domain.name -ne $null)
        {
            return "Authenticated"
        }
        Else
        {
            return "Not authenticated"
        }
    }
}

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

##############################################################
##        Text Frames
##############################################################
$Form           	             = New-Object system.Windows.Forms.Form
$Form.ClientSize    	             = '760,550'
$Form.text              	     = "Crear Script"
$Form.TopMost               	     = $false

$Label1       	                     = New-Object system.Windows.Forms.Label
$Label1.text    	             = "Folder path"
$Label1.AutoSize    	             = $true
$Label1.width           	     = 25
$Label1.height              	     = 10
$Label1.location                     = New-Object System.Drawing.Point(30,18)
$Label1.Font                         = 'Microsoft Sans Serif,10'

$TextBoxFolderPath                  = New-Object system.Windows.Forms.TextBox
$TextBoxFolderPath.multiline        = $false
$TextBoxFolderPath.width            = 500
$TextBoxFolderPath.height           = 10
$TextBoxFolderPath.location         = New-Object System.Drawing.Point(160,15)
$TextBoxFolderPath.Font             = 'Microsoft Sans Serif,10'
$TextBoxFolderPath.Text 	    = 'D:\Shares\Comercial'

$Label2             	             = New-Object system.Windows.Forms.Label
$Label2.text            	     = "Script Path"
$Label2.AutoSize            	     = $true
$Label2.width                        = 25
$Label2.height   	             = 10
$Label2.location    	             = New-Object System.Drawing.Point(30,58)
$Label2.Font            	     = 'Microsoft Sans Serif,10'

$TextBoxScriptPath                   = New-Object system.Windows.Forms.TextBox
$TextBoxScriptPath.multiline         = $false
$TextBoxScriptPath.width             = 500
$TextBoxScriptPath.height            = 10
$TextBoxScriptPath.location          = New-Object System.Drawing.Point(160,55)
$TextBoxScriptPath.Font              = 'Microsoft Sans Serif,10'
$TextBoxScriptPath.Text 	     = "ComercialScriptPath\%Username%.bat"

$TextBoxScript		             = New-Object system.Windows.Forms.TextBox
$TextBoxScript.multiline             = $true
$TextBoxScript.width		     = 500
$TextBoxScript.height		     = 390
$TextBoxScript.location  	     = New-Object System.Drawing.Point(35,135)
$TextBoxScript.Font 		     = New-Object System.Drawing.Font("Lucida Console",9,[System.Drawing.FontStyle]::Regular)

$Label3       	                     = New-Object system.Windows.Forms.Label
$Label3.text    	             = "Servidor: "
$Label3.AutoSize    	             = $true
$Label3.width           	     = 25
$Label3.height              	     = 10
$Label3.location                     = New-Object System.Drawing.Point(30,98)
$Label3.Font                         = 'Microsoft Sans Serif,10'

$TextBoxServer		             = New-Object system.Windows.Forms.TextBox
$TextBoxServer.multiline             = $false
$TextBoxServer.width		     = 500
$TextBoxServer.height		     = 28
$TextBoxServer.location  	     = New-Object System.Drawing.Point(160,95)
$TextBoxServer.Font 	             = 'Microsoft Sans Serif,10'
$TextBoxServer.text		     = "SRVDataShares"

$ButtonRead            		     = New-Object system.Windows.Forms.Button
$ButtonRead.text     	             = "Load script"
$ButtonRead.width 		     = 151
$ButtonRead.height             	     = 39
$ButtonRead.location                 = New-Object System.Drawing.Point(560,320)
$ButtonRead.Font                     = 'Microsoft Sans Serif,10'

$ButtonCreate                   	 = New-Object system.Windows.Forms.Button
$ButtonCreate.text               	 = "CREAR CARPETA"
$ButtonCreate.width                	 = 151
$ButtonCreate.height               	 = 39
$ButtonCreate.location            	 = New-Object System.Drawing.Point(560,375)
$ButtonCreate.Font                	 = 'Microsoft Sans Serif,10'


#################################################################
##
##    Script modifiying
##
#################################################################

$ButtonRead.Add_Click({
	
	$ScriptPath = -join("\\$domain\netlogon\",$TextBoxScriptPath.text )
		
	If ( Test-Path -path ( $ScriptPath ) )
	{
		# A Switch. This if statement changes the action done by the button from Read to Write and vice-versa. 
		if ($ButtonRead.Text -eq "Load script")
		{
			## `r`n are the default end_line for ps, 
			## Print line by line the content of the script in the textBoxScript
			$i = 0
			$Count = Get-Content -Path ($ScriptPath) | measure -Line | Select-Object -expand Lines
			$Line  = Get-Content -Path ($ScriptPath)
			while ($i -le $Count)
			{
				$TextBoxScript.AppendText($Line[$i])
				$TextBoxScript.AppendText("`r`n")
				$i++
			}
			$ButtonRead.Text = "**Save script**"
		}
		else
		{
			## Write TextBoxScript to the script file.
			$TextBoxScript.text | Out-File -FilePath $ScriptPath -Force
			$ButtonRead.Text = "Load script"
			
		}
	} Else {
		$TextBoxScript.text = "Script does not exist"
	}
})




#################################################################
##
##   Share creation and permission changes
##
#################################################################

$ButtonCreate.Add_Click({
	
	If (!(test-path -path $TextBoxFolderPath.text))
	{	
		# Test user existence
		$Path=$TextBoxFolderPath.text
		$SAMUser = $Path.split("\")[-1]
		try{
			Get-ADUser -Identity $SAMUser -server $domain
		} Catch {
			write-host "User does not exist"
			Break
		}
		
		# Loops the get-cred. Thanks to www.powershellbros.com
		$A=$true
		do 
		{
			$AdminCredential = Get-Credential
			if (($AdminCredential|Test-Cred) -ne "Authenticated" ) 
			{
				Write-Host "Wrong credentialss"
				$A=$False
			} 
			else 
			{
				$A=$True
			}
		} while ($A -eq $False)
		
		#Create remote session and make share changes. 
		$session = New-PSSession -ComputerName $TextBoxServer.text -Credential $AdminCredential
		Invoke-Command -Session $session -ScriptBlock { 		
		
			$Path=$using:TextBoxFolderPath.text
			$SAMUser = $Path.split("\")[-1]
			$User = -Join("$domain\",$SAMUser)	
			
			# Create Folder
			New-Item -ItemType directory -Path $Path	
			
			# Edit NTFS Permission
			$ACL = New-Object System.Security.AccessControl.DirectorySecurity
			
			# Disable inheritance
			$ACL.SetAccessRuleProtection($True, $True)
			
			# Add new permissions from scratch		
			$AR = New-Object system.security.accesscontrol.filesystemaccessrule("$domain\Domain Admins.","FullControl","ContainerInherit,ObjectInherit","None","Allow")
			$ARUsuario = New-Object system.security.accesscontrol.filesystemaccessrule ("$User","Read,Modify","ContainerInherit,ObjectInherit","None","Allow")
			$ACL.addAccessRule($AR)
			$ACL.addAccessRule($ARUsuario)
			
			Set-ACL -Path $Path -AclObject $ACL
			
			# Create Share. I use the batch command for compatibility with W2008. If you have 2012 you can use New-SMBShare
			net share $SAMUser'='$Path /grant:$User,change /grant:"$domain\Domain Admins.",full
			write-host "Finished"
		
		}
	}	
})

$Form.controls.AddRange(@($Label1, $TextBoxFolderPath, $Label2, $TextBoxScriptPath, $ButtonRead, $ButtonCreate, $TextBoxScript, $Label3, $TextBoxServer ))

[void]$Form.ShowDialog()

Posted Aug 20, 2019, 9:30 AM UTC

10

No comments yet

Nobody commented on this post, or the comments weren't captured.