For .NET 4.0, this command will install it for you if you have the Visual Studio 2019 files cached:
msiexec.exe /i "%ALLUSERSPROFILE%\Microsoft\VisualStudio\Packages\Microsoft.Net.4.TargetingPack,version=4.0.30319.1\netfx_dtp.msi" EXTUI=1
For .NET 4.5, this might work, though I haven't tried it:
msiexec.exe /i "%ALLUSERSPROFILE%\Microsoft\VisualStudio\Packages\Microsoft.Net.4.5.2.TargetingPack,version=4.5.51651.1\netfx_452mtpack.msi" EXTUI=1
build\.NETFramework\v4.5\ to C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5For more details: Building a project that target .NET Framework 4.5 in Visual Studio 2022
While all of the proposed, and even the accepted, solutions will work, none of them are the preferred approach.
The only thing you need to do is add a reference to the NuGet package as follows:
<ItemGroup>
<PackageReference Include="microsoft.netframework.referenceassemblies.net45"
Version="1.0.2" PrivateAssets="All" />
</ItemGroup>
You can make this change directly in the *.csproj or via the Package Manager UI in Visual Studio. The MSBuild extensions in the package will take care of the rest of the magic. There are no scripts to write, files to copy, or permissions to grant. This will work without elevation, which would be required to write under %PROGRAMFILES%.
Setting PrivateAssets="All" will make the package reference design-time only. It will not be picked up or included as a transitive dependency if your target also builds a NuGet package.
Roslyn Issue 56161: Remove .NET 4.5 Targeting Pack Requirement further confirms that this how you use reference assemblies when a targeting pack is not installed. This approach is useful any time you don't want to install a targeting pack or it's otherwise unavailable - say on a build server without Visual Studio.
I ran into the same issue after uninstalling Visual Studio 2019. The build worked as expected from Visual Studio and the CLI after adding this package reference.