Sonntag, 7. März 2010

PowerShell and Network Drives

Hello again,
PSDrives behave something different then mapped network drives and until now I still used a cmd script to map and unmap network drives.

But I just stumbled about some posts from The scripting guys and went back to Guy's Scripting Ezine 3 - Map Network Drive
where is told how to do it in vbs.

Finally I put it all together and translated it into the modern scripting language:

            
function New-NetworkDrive
{
<#
.synopsis
A function to create Networkdrives
.Example
New-NetworkDrive 'x' '\\localhost\C$'
.Example
New-NetworkDrive 'Y:' '\\localhost\C$\Windows'
#>

Param(
[string]$Drive,
[string]$Unc
)
$net = New-Object -com WScript.Network
if ($Drive.length -eq 1) { $Drive = $Drive +':' }
"$Drive $UNC"
$net.mapnetworkdrive($Drive, $Unc)
# ToDo -- currently I don#t need it
#$net.mapnetworkdrive($Drive+ ':',$Unc, $bProfile, $User, $password)
}


function Get-NetworkDrives
{
<#
.synopsis
A function to list the currently mapped Networkdrives
.Example
Get-NetworkDrives
#>

$mappedDrives = @{}
$net = New-Object -com WScript.Network
$a = $net.EnumNetworkDrives()
$anz = $a.count()

for ($i = 0; $i -lt $anz; $i = $i + 2)
{
$drive = $a.item($i)
$path = $a.item($i+1)
$mappedDrives[$drive] = $path
}
$mappedDrives
}

function Remove-NetworkDrive($Drive)
{
<#
.synopsis
A function to remove Networkdrives
.Example
Remove-NetworkDrive X
.Example
Remove-NetworkDrive Y:
#>

$net = New-Object -com WScript.Network
if ($Drive.length -eq 1) { $Drive += ':' }
$net.removenetworkdrive($Drive)
}


# see also
# http://www.computerperformance.co.uk/Logon/Logon_MapNetworkDrive.htm
# http://www.computerperformance.co.uk/Logon/LogonScript_enumnetworkdrives.htm#EnumNetworkDrives_Syntax

# http://www.computerperformance.co.uk/powershell/index.htm
# http://blogs.technet.com/heyscriptingguy/

Keine Kommentare:

Kommentar veröffentlichen