windowsbatch-filenet-use

Simple PowerShell script to make a directory share it with everyone permission and map it as a shared network drive


I'm trying to automate a simple but repetitive task for a non-it-literate friend. I'm a TV editor, but I have a simple working knowledge of this, so I appreciate your skill and knowledge.

On a Windows PC, with PowerShell available, I'd like a script (I'd really like a GUI but that would be dreaming), to

  1. Create a new directory in a specific hard coded location - checking that no existing directory of the same name exists, etc.

  2. The new directory is shared with everyone, full read/write permission

  3. The new directory is mapped, as persistent with the next available drive letter, skipping optical media / card reader drive letters.

NB: As mentioned, the network share has to be persistent after a reboot.

Research suggests for 1 (but needs more to check for duplicates, etc.):

# PowerShell creates a folder
$Location = "X:\Clients\"
New-Item -Path $Location -Name "My_New_Folder" -ItemType "directory"
#Invoke-Item $Location

Research suggests for 2: ? No Idea where to start

Research suggests for 3:

@echo off
setlocal

call :freedrive mydriveletter && goto :cont
echo ERROR: No free drive letter found.
goto :exit
:cont
echo Found drive letter: %mydriveletter%

goto :exit

rem Finds a free drive letter.
rem
rem Parameters:
rem     %1 = Output variable name.
rem
rem Example:
rem     call :freedrive mydriveletter && goto :cont
rem     echo ERROR: No free drive letter found.
rem     goto :EOF
rem     :cont
rem     echo Found drive letter: %mydriveletter%
:freedrive
setlocal EnableDelayedExpansion
set exitcode=0
set "output_var=%~1"
for %%i in (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z) do (
    set "drive=%%i:"
    rem If 'subst' fails, the drive letter is already in use.
    rem This way we can even detect optical drives that have a drive
    rem letter but no media in them, a case that goes undetected when
    rem using 'if exist'.
    subst !drive! %SystemDrive%\ >nul
    if !errorlevel! == 0 (
        subst !drive! /d >nul
        goto :freedrive0
    )
)
set exitcode=1
set drive=
:freedrive0
endlocal & set "%output_var%=%drive%" & exit /b %exitcode%

:exit
pause

Solution

  • So I think I have solved my own problem, the syntax / grammar was confusing for a newbie to pass variables along...

    # create a folder with user input
    $folder = Read-Host 'Name a new directory to be created in the Clients folder'
    $Location = "C:\Clients\"
    New-Item -Path $Location -Name "$folder" -ItemType "directory"
    # set permission
    icacls "$Location$folder" /grant everyone:F
    # share folder
    net share $folder="$Location$folder" /GRANT:EVERYONE`,FULL
    # map folder as drive
    net use * /persistent:yes \\localhost\$folder