Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # PowerShell script to automate network drive mapping without manual user interaction
- # Set network path and default drive letter
- $networkPath = "\\192.168.1.3\Documents" # Change this to the correct network path
- $driveLetter = "Z:" # Drive letter to map
- # Function to check if a drive letter is already in use
- function Test-DriveLetter {
- param (
- [string]$driveLetter
- )
- $drive = Get-PSDrive -Name $driveLetter -ErrorAction SilentlyContinue
- return $drive -ne $null
- }
- # Function to create and securely handle user credentials
- function Get-UserCredentials {
- # Prompt user for credentials if needed
- $username = Read-Host "Enter your network username"
- $password = Read-Host "Enter your network password" -AsSecureString
- return New-Object System.Management.Automation.PSCredential ($username, $password)
- }
- # Function to test network connection to the remote server
- function Test-NetworkConnection {
- param (
- [string]$networkPath
- )
- $hostname = $networkPath.Split("\")[2]
- try {
- $pingResult = Test-Connection -ComputerName $hostname -Count 1 -Quiet
- if ($pingResult) {
- Write-Host "Network connection to $hostname is successful."
- return $true
- } else {
- Write-Host "Error: Cannot reach $hostname."
- return $false
- }
- } catch {
- Write-Host "Error: $($_.Exception.Message)"
- return $false
- }
- }
- # Function to map the network drive
- function Map-NetworkDrive {
- param (
- [string]$driveLetter,
- [string]$networkPath,
- [System.Management.Automation.PSCredential]$credential
- )
- # Check if drive letter is already in use
- if (Test-DriveLetter -driveLetter $driveLetter) {
- Write-Host "Error: Drive letter $driveLetter is already in use. Please choose another one."
- return
- }
- # Check network connection
- if (Test-NetworkConnection -networkPath $networkPath) {
- try {
- # Attempt to map the network drive
- New-PSDrive -Name "MappedDrive" -PSProvider FileSystem -Root $networkPath -Persist -Scope Global -Credential $credential
- Write-Host "Network drive mapped successfully to $driveLetter."
- } catch {
- Write-Host "Error mapping network drive: $($_.Exception.Message)"
- }
- } else {
- Write-Host "Error: Unable to reach the network path $networkPath."
- }
- }
- # Main script execution
- Write-Host "Starting network drive mapping process..."
- # Prompt for credentials
- $credential = Get-UserCredentials
- # Call the function to map the network drive
- Map-NetworkDrive -driveLetter $driveLetter -networkPath $networkPath -credential $credential
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement