Friday, December 17, 2010

Create Windows Share on a remote computer

This subroutine will add a Windows (or NT) share to any computer provided you have a user with permission on that machine.
Private Sub CreateShare(strShareName, strPath, strDescription, strComputer, strDomain, strUser, strPassword) 
    Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator") 
    Set objSWbemServices = objSWbemLocator.ConnectServer(strComputer, _
         "root\cimv2", strUser, strPassword, "MS_409", "ntlmdomain:" + strDomain) 
    Set colSwbemObjectSet = objSWbemServices.InstancesOf("Win32_Share") 

    For each objSWbem in colSwbemObjectSet 
        If(objSWbem.name = strShareName)Then  
            blnShareExists = True 
            Exit For 
        Else            
            blnShareExists = False 
        End If 
    Next  

    If (blnShareExists = False)Then 
        set objSWbemObject = objSWbemServices.Get("Win32_Share")  
        intRet = objSWbemObject.Create(strPath, strShareName, 0, _
            10, strDescription) 
    End If 
    msgbox(intret) 
End Sub
Sample call:
CreateShare "Share1", "D:\mydir", "this is mydir", "MyComp", "MyDomain.Net", "MyUser" , "MyPassword"

Thursday, December 16, 2010

Map Network Drive with a users credentials


Three quick and easy ways to Map a UNC path to a local drive. The samples below (DOS, VBS, PowerShell) map the Q: drive to a network path using different credentials. you can also remove the parameters for credentials and it will create the connection with the current logged-on user.

DOS
NET USE Q: \\MyUnc\Path /USER:MyUser MyPassword

VBS

strDrive = "Q:"
strUNC = "\\MyUnc\Path"
strProfile = "False"   ' Mapping (not) stored in user Profile
strUser = "MyUser"
strPassword = "MyPassword"
Set objNetwork = CreateObject("WScript.Network") 
objNetwork.MapNetworkDrive strDrive, strUNC, strProfile, strUser, strPassword 

Powershell

$Drive = "Q:"
$UNC = "\\MyUnc\Path"
$Profile = "False"
$User = "MyUser"
$Password = "MyPassord"
$Network = New-Object -com WScript.Network; 
$Network.mapnetworkdrive($Drive,$Unc, $Profile, $User, $Password)

The code above is basically the same as done in VBS, You can also make the DOS call in Powershell.