Powershell

Powershell 從 CSV 集變數中讀取

  • August 7, 2020

我有一個包含兩列“路徑”和“所有者”的 csv 文件。

我創建了以下腳本,它可以從 CSV 文件中讀取,但是當我嘗試從 csv 分配變數時它失敗了。

Import-Csv C:\test\output.csv | ForEach-Object {
   $Path = $_.path
   $owner = $_.owner
   "The username is $Path and the owner is $owner"
}
ForEach-Object {
   $Path = $_.path
   $owner = $_.owner

   $Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList '$owner'
   $Acl = Get-Acl -Path $Path
   $Acl.SetOwner($Account)

   Set-Acl -Path $owner -AclObject $Acl
}

第一段的輸出是正確的,並顯示了路徑和所有者,但第二部分沒有根據路徑設置所有者。

第二個 foreach 沒有要迭代的輸入對象。所以要麼

  • 導入到變數並將其通過管道兩次傳遞到 foreach 循環
  • 導入兩次

$csv = import-csv c:\test\output.csv 
$csv | foreach-object {
 $Path = $_.path
 $owner =$_.owner
 "The username is $Path and the owner is $owner"
}
$csv | ForEach-Object {
   $Path = $_.path
   $owner =$_.owner
   $Account = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList "$owner"
   $Acl = Get-Acl -Path $path
   $Acl.SetOwner($Account);
   Set-Acl -Path $Path -AclObject $Acl
}

引用自:https://serverfault.com/questions/839261