情况: 我以管理员身份运行Visual Studio。 我使用该脚本初始化我的解决方案。其中一个初始化任务是设置主机文件条目。 我在目标BeforeBuild:
中的构建过程中在csproj文件中执行powershell脚本<Target Name="BeforeBuild">
<PropertyGroup>
<InitScriptPath Condition=" '$(InitScriptPath)' == '' ">$(SolutionDir)Scripts\InitKentico.ps1</InitScriptPath>
<KenticoVersion Condition=" '$(KenticoVersion)' == '' ">10.0.0</KenticoVersion>
<KenticoProjectName Condition=" '$(KenticoProjectName)' == '' ">Kentico10WebAppDemo</KenticoProjectName>
<KenticoWebsiteBinding Condition=" '$(KenticoWebsiteBinding)' == '' ">local.kentico10webappdemo.com</KenticoWebsiteBinding>
<InitScriptCommand Condition=" '$(InitScriptCommand)' == '' ">%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe -command "& { &'$(InitScriptPath)' '$(ProjectDir)' '$(SolutionDir)' '$(KenticoVersion)' '$(KenticoProjectName)' '$(KenticoWebsiteBinding)'; exit $lastexitcode }"</InitScriptCommand>
</PropertyGroup>
<Message Text="Running Init PowerShell Script: $(InitScriptPath) with command $(InitScriptCommand)" Importance="high" />
<Exec Command="$(InitScriptCommand)" />
如果脚本以管理员身份执行,我会在PowerShell中查看:
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if (-not($myWindowsPrincipal.IsInRole($adminRole))) {
Write-Host "Must be executed as administrator!"
exit 1
}
我使用以下脚本编辑主机文件:
$file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"
$data = Get-Content -Path $file
$entriesBlockHeader = "### MyWebsite ###";
$hostEntry1 = "127.0.0.1`tmy-website.com"
$hostEntry2 = "127.0.0.1`twww.my-website.com"
$entriesBlock = [System.Environment]::NewLine + $entriesBlockHeader
$entriesBlock = $entriesBlock + [System.Environment]::NewLine + $hostEntry1
$entriesBlock = $entriesBlock + [System.Environment]::NewLine + $hostEntry2
$data = $data + $entriesBlock
$data | Out-File -FilePath $file
我的问题: 在更改主机文件时,脚本会抛出异常,因为权限被拒绝。 我不明白为什么会这样。该脚本以管理员身份执行,因此它应具有所需的权限。 当我在Powershell ISE中执行脚本(作为管理员)时,它就像一个魅力。只有从Visual Studio中的csproj文件(作为管理员)执行它才能正常工作。