Skip to content

Bug: Add-Type needs write-access when compiling from source #7914

@IISResetMe

Description

@IISResetMe

I was curious to find this reddit post describing how Add-Type -Path ./path/to/sourcecode.cs fails with Access to the path './path/to/sourcecode.cs' is denied even though the process owner has read access to the file.

Upon granting write access to the file, the issue resolves.

Steps to reproduce

I've only tested this on Windows 10:

# Create empty source file
$srcFile = Get-Item $([System.IO.Path]::GetTempFileName()) |Rename-Item -NewName {$_.BaseName + '.cs'} -PassThru
# Write source code to file
@'
using System;
namespace TestAddType {
  public class TestClass {}
}
'@ |Set-Content $srcFile -Encoding UTF8
# Mark source file ReadOnly
$srcFile.Attributes += 'ReadOnly'
# Attempt to compile from source
Add-Type -Path $srcFile.FullName
# Output new type literal
[TestAddType.TestClass]

Expected behavior

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    TestClass                                System.Object

Actual behavior

Add-Type : Access to the path 'C:\Users\iisresetme\AppData\Local\Temp\tmp2A59.cs' is denied.
At line:1 char:1
+ Add-Type -Path $srcFile.FullName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Add-Type], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.AddTypeCommand

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.1.0
PSEdition                      Core
GitCommitId                    6.1.0-57-g0f0c46dfe51440470b86f67b258e14aea32fa0aa
OS                             Microsoft Windows 10.0.17134 
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugIssue has been identified as a bug in the productResolution-FixedThe issue is fixed.WG-Cmdlets-Utilitycmdlets in the Microsoft.PowerShell.Utility module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions