Skip to content

Commit 2475feb

Browse files
Enable usage in AppContainers (PowerShell#27266)
Co-authored-by: Travis Plunk <travis.plunk@microsoft.com>
1 parent 6cc1e70 commit 2475feb

2 files changed

Lines changed: 28 additions & 3 deletions

File tree

src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -967,7 +967,9 @@ internal static string GetPersonalModulePath()
967967
#if UNIX
968968
return Platform.SelectProductNameForDirectory(Platform.XDG_Type.USER_MODULES);
969969
#else
970-
string myDocumentsPath = InternalTestHooks.SetMyDocumentsSpecialFolderToBlank ? string.Empty : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
970+
string myDocumentsPath = InternalTestHooks.SetMyDocumentsSpecialFolderToBlank
971+
? string.Empty
972+
: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify);
971973
return string.IsNullOrEmpty(myDocumentsPath) ? null : Path.Combine(myDocumentsPath, Utils.ModuleDirectory);
972974
#endif
973975
}

src/System.Management.Automation/namespaces/FileSystemProvider.cs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive)
569569
if (driveIsFixed)
570570
{
571571
// Since the drive is fixed, ensure the root is valid.
572-
validDrive = Directory.Exists(drive.Root);
572+
validDrive = SafeDoesPathExist(drive.Root);
573573
}
574574

575575
if (validDrive)
@@ -908,7 +908,7 @@ protected override Collection<PSDriveInfo> InitializeDefaultDrives()
908908

909909
if (newDrive.DriveType == DriveType.Fixed)
910910
{
911-
if (!newDrive.RootDirectory.Exists)
911+
if (!SafeDoesPathExist(newDrive.RootDirectory.FullName))
912912
{
913913
continue;
914914
}
@@ -1227,6 +1227,29 @@ protected override void GetItem(string path)
12271227
}
12281228
}
12291229

1230+
private static bool SafeDoesPathExist(string rootDirectory)
1231+
{
1232+
if (Directory.Exists(rootDirectory))
1233+
{
1234+
return true;
1235+
}
1236+
1237+
try
1238+
{
1239+
return (File.GetAttributes(rootDirectory) & FileAttributes.Directory) is not 0;
1240+
}
1241+
// In some scenarios (like AppContainers) direct access to the root directory may
1242+
// be prevented, but more specific paths may be accessible.
1243+
catch (UnauthorizedAccessException)
1244+
{
1245+
return true;
1246+
}
1247+
catch
1248+
{
1249+
return false;
1250+
}
1251+
}
1252+
12301253
private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool showHidden)
12311254
{
12321255
path = NormalizePath(path);

0 commit comments

Comments
 (0)