以管理员身份运行脚本时出现问题。当我以普通用户身份运行时,该脚本仅适用于我的帐户。由于该脚本是以管理员身份运行的,因此它将为所有登录过该计算机的用户执行。该脚本位于C:\Users目录中。
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
$path = "Users"
$fileTypes = ".*.vbox"
$files = Get-ChildItem -Recurse | Where-Object FullName -Match ".*$path*" -ErrorAction SilentlyContinue
$counter = 1
$dir = ""
foreach ($file in $files) {
$name = $file.Name
$fullname = $file.FullName
$fullname2 = "qwefd"
$extension = $file.Extension
$extXML = "$fullname"+".xml"
if ($name -Match $fileTypes) {
if ($dir -ne $file.Directory.Name) {
$dir = $file.Directory.Name
}
Rename-Item $fullname $extXML
$xmlFileName = $extXML
# Read the existing file
[xml]$xmlDoc = Get-Content $xmlFileName
# If it was one specific element you can just do like so:
$xmlDoc.VirtualBox.Machine.Hardware.Network.Adapter.InnerText = "<NAT/>"
# however this wont work since there are multiple elements
# Since there are multiple elements that need to be
# changed use a foreach loop
foreach ($element in $xmlDoc.VirtualBox.Machine.Hardware.Network)
{
$element.Adapter.InnerText = "<NAT/>"
}
# Then you can save that back to the xml file
$xmlDoc.Save($xmlFileName)
$con = Get-Content $xmlFileName
$con | % { $_.Replace("<", "<") } | Set-Content $xmlFileName
$con2 = Get-Content $xmlFileName
$con2 | % { $_.Replace(">", ">") } | Set-Content $xmlFileName
Rename-Item $extXML $fullname
}
}
pause我以Admin身份运行此脚本,并获得以下内容:
Get-ChildItem : Access to the path „C:\WINDOWS\system32\LogFiles\WMI\RtBackup” is denied.
At C:\Users\Forcing_NAT_on_VMs.ps1:11 char:10
+ $files = Get-ChildItem -Recurse | Where-Object FullName -Match ".*$pa ...
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\WINDOWS\syst...es\WMI\RtBackup:String) [Get-ChildItem], Unauthoriz
edAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand发布于 2021-11-20 14:24:32
当没有为命令定义文件夹路径时,我遇到了相同的错误
Get-ChildItem 例如,未定义FullName
$files = Get-ChildItem -Recurse | Where-Object FullName -Match ".*$path*" -ErrorAction SilentlyContinue发布于 2021-04-01 08:48:36
我建议在Get-ChildItem中使用-ErrorAction SilentlyContinue
https://stackoverflow.com/questions/61775339
复制相似问题