Pergunta

I created a SmartCreateShare function in PowerShell. The objective is creating a SMB share, deleting any previous existing share with same name. I am executing this script in a Windows 2008 R2 with PowerShell 3.0 so I am using net share commands. Here is the function

function SmartCreateShare($folder, $shareName, $shareUser, $sharePermissions)
{
    #Detect previous Share
    $shares = net share
    Foreach ($Key in ($shares.GetEnumerator() ))
    {
        #Write-host $Key
        if ($Key.Contains($shareName)) 
        { 
            NET SHARE $shareName /DELETE | Out-Null
            Write-host "Deleted share $shareName"
        }
    }

    # Create Share
    NET SHARE $shareName=$folder "/GRANT:$shareUser,READ" | Out-Null
    Write-host "Shared $folder with sharename: $shareName"

}

The invocation is

SmartCreateShare $baseBackupFolder "IddnBackups" "Everyone" "READ"

The script works fine, but I think the way I am iterating the output of "Net Share" command is not the best one.

Is possible to improve the script to use Where-Object or similar instead of iterating using the enumerator?

Foi útil?

Solução

Net Share is just returning an array of strings. You could replace thise:

Foreach ($Key in ($shares.GetEnumerator() ))
    {
      #Write-host $Key
      if ($Key.Contains($shareName)) 
      { 
        NET SHARE $shareName /DELETE | Out-Null
        Write-host "Deleted share $shareName"
      }
    }

With something like this:

if ((net share) -match "^$shareName\s")
  {
    NET SHARE $shareName /DELETE | Out-Null
    Write-host "Deleted share $shareName"
  }

Outras dicas

I'd recommend using WMI instead of fumbling around with net share (code for share creation shamelessly stolen from here):

function SmartCreateShare($folder, $shareName, $shareUser, $sharePermissions) {
  $permissions = @{
    'read'   = 117978
    'change' = 1245631
    'full'   = 2032127
  }

  # delete existing share
  gwmi Win32_Share -Filter "Name = '$shareName'" | % { $_.Delete() } | Out-Null

  $trustee = ([wmiclass]'Win32_Trustee').PSBase.CreateInstance()
  $trustee.Domain = 'domain'
  $trustee.Name   = $shareUser

  $ace = ([wmiclass]'Win32_Ace').PSBase.CreateInstance()
  $ace.AccessMask = $permissions[$sharePermissions]
  $ace.AceFlags   = 3
  $ace.AceType    = 0
  $ace.Trustee    = $trustee

  $sd = ([wmiclass]'Win32_SecurityDescriptor').PSBase.CreateInstance()
  $sd.ControlFlags = 4
  $sd.DACL  = $ace
  $sd.group = $trustee
  $sd.owner = $trustee

  # re-create share
  (gwmi Win32_Share).Create($folder, $shareName, 0, 100, '', '', $sd)
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top