2016-09-22 43 views
0

這裏是我的代碼,我已經包括相關部分:無法覆蓋變量假的,因爲它是隻讀或常量

Get-ChildItem -LiteralPath $somepath -Directory | ForEach-Object { 
    Step $_.FullName 
} 

function Step { 
    Param([string]$subfolder) 

    $folders = Get-ChildItem -LiteralPath $subfolder -Directory -ErrorVariable $HasError -ErrorAction SilentlyContinue 

    if ($HasError) { 
     Write-Host $_.FullName "|" $HasError.Message 
     return 
    } else { 
     $hasError, $inactive = FolderInactive $_.FullName 
     if ($hasError) { 
      #do nothing 
     } else { 
      if ($inactive) { 
       SetFolderItemsReadOnly $_.FullName 
      } 
     } 
    } 

    if ($folders) { 
     $folders | ForEach-Object { 
      Step $_.FullName 
     } 
    } 
} 

function SetFolderItemsReadOnly { 
    Param([string]$Path) 

    $files = Get-ChildItem -LiteralPath $Path -File -ErrorAction Stop 

    foreach ($file in $files) { 
     try { 
      Set-ItemProperty -LiteralPath $file.FullName -Name IsReadOnly -Value $true 
     } catch { 
      Write-Host $file.FullName " | " $_.Exception.Message 
     }  
    } 
} 

我得到了一些錯誤與在SetFolderItemsReadOnly功能Set-ItemProperty,即

例外設置「IsReadOnly」:「訪問路徑被拒絕。」

這是由於一些安全權限。在終端上打印此錯誤後,但是我也得到一個巨大的紅色的錯誤,像這樣:

Cannot overwrite variable false because it is read-only or constant. 
At pathtoscript:55 char:5 
+  $folders = Get-ChildItem -LiteralPath $subfolder -Directory -ErrorVariable ... 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : WriteError: (false:String) [], SessionStateUnauthorizedAccessException 
    + FullyQualifiedErrorId : VariableNotWritable

爲什麼會出現這種錯誤發生的呢?

+0

沒你嘗試以管理員身份運行你的腳本? –

+2

我會得到您的$ HasError變量被初始化爲true,並在您的Get-ChildItem調用期間進行評估。嘗試在-ErrorVariable調用中刪除名稱前面的「$」。 –

+0

@MartinBrandl我有。有些文件即使是我們的管理員也不能均勻寫入,我不知道爲什麼。但是,它應該只打印「異常設置」IsReadOnly「等」,但有時它也會出現奇怪的錯誤。 –

回答

2

由於@DavidBrabant指出,參數-ErrorVariable只需要變量的名稱,沒有前導$。此外,不管是否發生錯誤(PowerShell已通過automatic variable$?提供此信息),該變量的目的都不是布爾指示符,而是接收實際的錯誤對象。

documentation

-ErrorVariable [+]<variable-name> 

別名:ev

商店錯誤有關指定變量,並且在$Error自動變量的命令消息。有關詳細信息,輸入以下命令:

get-help about_Automatic_Variables 

默認情況下,新的錯誤消息覆蓋已存儲在變量的錯誤消息。要將錯誤消息追加到變量內容中,請在變量名稱前面輸入加號(+)。

例如,下面的命令創建$a變量並存儲在它的任何錯誤:

Get-Process -Id 6 -ErrorVariable a 

以下命令將任何錯誤信息到$a變量:

Get-Process -Id 2 -ErrorVariable +a