如何在powershell中使用for循环来获取多个变量值

时间:2014-10-29 15:04:31

标签: powershell

我正在尝试创建一个网络共享和设置ACL权限,它适用于1个文件夹,但我想为另外1个文件夹创建相同的东西,我只是不想重复代码。

以下是我的1个文件夹的工作代码,我也会把其他文件夹的路径

$MediaFoler_Security = 'C:\Projects\MediaContent'
$acl = Get-Acl $MediaFoler_Security
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS_IUSRS","FullControl",   
"ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $MediaFoler_Security $acl

这是我的其他文件夹路径

$DeployFolder_Security = 'C:\Projects\Deployments'

2 个答案:

答案 0 :(得分:1)

把它放在一个函数中:

function my-acl($path) {
  $acl = Get-Acl $path
  $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS_IUSRS","FullControl",   
  "ContainerInherit, ObjectInherit", "None", "Allow")
  $acl.AddAccessRule($rule)
  Set-Acl $path $acl
}

并致电:

my-acl 'C:\Projects\MediaContent'
my-acl 'C:\Projects\Deployments'

或者:

$dirs = @('C:\Projects\MediaContent','C:\Projects\Deployments')
$dirs | % { my-acl $_ }

答案 1 :(得分:0)

你可以这样做:

$folders = "C:\Projects\Mediacontent","C:\Projects\Deployments"

foreach($folder in $folders){

$acl = Get-Acl $folder
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS_IUSRS","FullControl",   
"ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $folder $acl

}