0

I have a script that needs to be modified to create a folder on the desktop and share with everyone if it does not exist on a Windows 7 PC - No Domain. Here is the script, need help at bottom =======================================================

Set objShell = CreateObject("WScript.Shell")
objComputer=objShell.ExpandEnvironmentStrings("%ComputerName%")
IF Right(objComputer,3) = "000" Then

Else

strShortcut = objShell.SpecialFolders( "Desktop" )  & "\%username% Share.lnk"
strShortcut = objShell.ExpandEnvironmentStrings(strShortcut)

Set objLink = objShell.CreateShortcut( strShortcut ) 

objComputer=objShell.ExpandEnvironmentStrings("%ComputerName%")
objServer=Left(objComputer,7) & "-000"

objLink.Description = objShell.ExpandEnvironmentStrings("%username% Share")
objLink.TargetPath = objShell.ExpandEnvironmentStrings("\\" & objServer & "\Users\%username%\Desktop\%username% Share")
objLink.Save

End If

=======================================================

if "C:\Users\%username%\desktop\%username% Share" exits do nothing

if not create the folder and share it with everyone read only

The two if statements above is what I need to add, anyone have a clue how to make this work?

1 Answers1

1

In VBScript you'd use a FileSystemObject instance to handle the folder and WMI to handle the share:

path = "%USERPROFILE%\Desktop\%USERNAME% Share"

Set sh  = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")

path = sh.ExpandEnvironmentStrings(path)

If Not fso.FolderExists(path) Then
  'create the folder
  fso.CreateFolder path

  'create the share
  Set wmi = GetObject("winmgmts://./root/cimv2")

  Set trustee = wmi.Get("Win32_Trustee").SpawnInstance_()
  trustee.Domain = Null
  trustee.Name   = "Everyone"
  trustee.SID    = Array(1,1,0,0,0,0,0,1,0,0,0,0) 'SID S-1-1-0 (binary)

  Set ace = wmi.Get("Win32_Ace").SpawnInstance_()
  ace.AccessMask = 1179817  'read/execute access
  ace.AceFlags   = 3        'object inheritance + container inheritance
  ace.AceType    = 0        'allow access
  ace.Trustee    = trustee

  Set sd = wmi.Get("Win32_SecurityDescriptor").SpawnInstance_()
  sd.DACL = Array(ace)

  Set share = wmi.Get("Win32_Share")
  rc = share.Create(path, fso.GetFileName(path), 0, 10, "", "", sd)
End If

It may be simpler to do this in batch, though:

@echo off

set "fldr=%USERPROFILE%\Desktop\%USERNAME% Share"
for %%n in ("%fldr%") do set "name=%%~nxn"

if not exist "%fldr%" (
  mkdir /p "%fldr%"
  net share "%name%"="%fldr%" /grant:Everyone,READ
)

Addendum: Note that the CreateFolder function expects that the parent folder of the folder you want to create already exists. In your particular scenario (the user's desktop folder) that can reasonably be assumed. However, if someone wanted to apply this to a more general scenario, they'd need to use a recursive function to create the parent folder(s) as well as the child folder.

Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328