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
爲什麼會出現這種錯誤發生的呢?
沒你嘗試以管理員身份運行你的腳本? –
我會得到您的$ HasError變量被初始化爲true,並在您的Get-ChildItem調用期間進行評估。嘗試在-ErrorVariable調用中刪除名稱前面的「$」。 –
@MartinBrandl我有。有些文件即使是我們的管理員也不能均勻寫入,我不知道爲什麼。但是,它應該只打印「異常設置」IsReadOnly「等」,但有時它也會出現奇怪的錯誤。 –