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“等”,但有时它也会出现奇怪的错误。 –