forked from jdhitsolutions/PSScriptTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNew-PSDriveHere.ps1
More file actions
97 lines (77 loc) · 2.62 KB
/
New-PSDriveHere.ps1
File metadata and controls
97 lines (77 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
Function New-PSDriveHere {
[cmdletBinding(SupportsShouldProcess = $True, DefaultParameterSetName = "Folder")]
[OutputType([System.Management.Automation.PSDriveInfo])]
[Alias("npsd")]
Param(
[Parameter(Position = 0)]
[ValidateScript( {Test-Path $_})]
[string]$Path = ".",
[Parameter(Position = 1, ParameterSetName = "Name")]
[ValidateNotNullorEmpty()]
[string]$Name,
[Parameter(ParameterSetName = "Folder")]
[switch]$First,
[Alias("cd")]
[switch]$SetLocation,
[Parameter(HelpMessage="Pass the new PSDrive object to the pipeline.")]
[switch]$Passthru
)
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "Getting the location for $path"
#get the specified location
$location = Get-Item -Path $path
#did the user specify a name?
if ($pscmdlet.ParameterSetName -eq "Name") {
Write-Verbose "Defining a new PSDrive with the name $Name."
} #if $name
else {
if ($first) {
Write-Verbose "Using the first word in the target location."
$pattern = "^\w+"
}
else {
Write-Verbose "Using the last word in the target location."
$pattern = "\w+$"
}
#Make sure name contains valid characters. This function
#should work for all but the oddest named folders.
if ($location.Name -match $pattern) {
$name = $matches[0]
}
else {
#The location has something odd about it so bail out
Write-Warning "$path doesn't meet the criteria"
Break
}
} #else using part of folder name
#verify a PSDrive doesn't already exist
Write-Verbose "Testing $($name):"
If (-not (Test-Path -path "$($name):")) {
Write-Verbose "Creating PSDrive for $name"
$paramHash = @{
Name = $name
PSProvider = $location.PSProvider
Root = $Path
Description = "Created $(Get-Date)"
Scope = 'Global'
ErrorAction = 'Stop'
}
Try {
$result = New-PSDrive @paramHash
if ($Passthru) {
$result
}
if ($SetLocation) {
Write-Verbose "Setting location to $($name):"
Set-Location -Path "$($name):"
}
} #try
Catch {
Write-Error $_
}
} #if Not Test-Path
else {
Write-Warning "A PSDrive for $name already exists"
}
Write-Verbose "Ending: $($MyInvocation.Mycommand)"
} #function