'Check if a path is a folder or a file in PowerShell

I'm trying to write a PowerShell script which goes through a list of values which are folder or file paths, and delete the files first, then remove the empty folders.

My script so far:

[xml]$XmlDocument = Get-Content -Path h:\List_Files.resp.xml
$Files =  XmlDocument.OUTPUT.databrowse_BrowseResponse.browseResult.dataResultSet.Path

Now I'm trying to test each line in the variable to see if it's a file and delete it first, and then go through and remove subfolders and folders. This is just so that it's a clean process.

I can't quite get this next bit to work, but I think I need something like:

foreach ($file in $Files)
{
    if (! $_.PSIsContainer)
    {
        Remove-Item $_.FullName}
    }
}

The next section can clean up the subfolders and folders.

Any suggestions?



Solution 1:[1]

I found a workaround for this question: use Test-Path cmdlet with the parameter -FileType equal to Leaf for checking if it is a file or Container for checking if it is a folder:

# Check if file (works with files with and without extension)
Test-Path -Path 'C:\Demo\FileWithExtension.txt' -PathType Leaf
Test-Path -Path 'C:\Demo\FileWithoutExtension' -PathType Leaf

# Check if folder
Test-Path -Path 'C:\Demo' -PathType Container

Demo

I originally found the solution here. And the official reference is here.

Solution 2:[2]

I think that your $Files object is an array of strings:

PS D:\PShell> $Files | ForEach-Object {"{0} {1}" -f $_.Gettype(), $_}
System.String D:\PShell\SO
System.String D:\PShell\SU
System.String D:\PShell\test with spaces
System.String D:\PShell\tests
System.String D:\PShell\addF7.ps1
System.String D:\PShell\cliparser.ps1

Unfortunately, the PSIsContainer property cannot be found on a string object but on a filesystem object, e.g.

PS D:\PShell> Get-ChildItem | ForEach-Object {"{0} {1}" -f $_.Gettype(), $_}
System.IO.DirectoryInfo SO
System.IO.DirectoryInfo SU
System.IO.DirectoryInfo test with spaces
System.IO.DirectoryInfo tests
System.IO.FileInfo addF7.ps1
System.IO.FileInfo cliparser.ps1

To get a filesystem object from a string:

PS D:\PShell> $Files | ForEach-Object {"{0} {1}" -f (Get-Item $_).Gettype(), $_}
System.IO.DirectoryInfo D:\PShell\SO
System.IO.DirectoryInfo D:\PShell\SU
System.IO.DirectoryInfo D:\PShell\test with spaces
System.IO.DirectoryInfo D:\PShell\tests
System.IO.FileInfo D:\PShell\addF7.ps1
System.IO.FileInfo D:\PShell\cliparser.ps1

Try next code snippet:

$Files | ForEach-Object 
  {
    $file = Get-Item $_               ### string to a filesystem object
    if ( -not $file.PSIsContainer)
        {
            Remove-Item $file}
        }
  }

Solution 3:[3]

We can use get-item command and supply the path. Then you can check PSIsContainer (boolean) property that would determine whether the supplied path targets a folder or a file. e.g.

$target = get-item "C:\somefolder" # or "C:\somefolder\somefile.txt"
if($target.PSIsContainer) {
# it's a folder
}
else { #its a file }

Hope this helps any future visitors.

Solution 4:[4]

Consider the following code:

$Files = Get-ChildItem -Path $env:Temp

foreach ($file in $Files)
{
    $_.FullName
}

$Files | ForEach {
    $_.FullName
}

The first foreach is a PowerShell language command for looping, and the second ForEach is an alias for the ForEach-Object cmdlet which is something completely different.

In the ForEach-Object, the $_ points to the current object in the loop, as piped in from the $Files collection, but in the first foreach, $_ has no meaning.

In the foreach loop use the loop variable $file:

foreach ($file in $Files)
{
    $file.FullName
}

Solution 5:[5]

Yet another way is by using DirectoryInfo.

MWE from the file-name:

$(Get-Item c:\windows\system32) -is [System.IO.DirectoryInfo]

Solution 6:[6]

Using Pip, Conda, Docker image & Dockerfile we can create ML environments for your own scripts.

I want to be able to create a specific environment

To manually create an environment,

from azureml.core.environment import Environment
Environment(name="myenv")

Use Conda dependencies or pip requirement files for creating an environment using below code:

#### From a Conda specification file
myenv = Environment.from_conda_specification(name = "myenv",
                                             file_path = "path-to-conda-specification-file")

#### From a pip requirements file
myenv = Environment.from_pip_requirements(name = "myenv",
                                          file_path = "path-to-pip-requirements-file")

The environment that the Notebook seems to run does not contain the packages I need and I want to preserve different environments.

To add the packages to your environment, can use the Conda, pip or private wheel files but it is recommended to use CondaDependency class.

from azureml.core.environment import Environment
from azureml.core.conda_dependencies import CondaDependencies

myenv = Environment(name="myenv")
conda_dep = CondaDependencies()

#### Installs numpy version 1.17.0 conda package
conda_dep.add_conda_package("numpy==1.17.0")

#### Installs pillow package
conda_dep.add_pip_package("pillow")

#### Adds dependencies to PythonSection of myenv
myenv.python.conda_dependencies=conda_dep

Register your environment in workspace using the command myenv.register(workspace=ws)

list(workspace) the list the environments in the workspace

To run your specific environment:

from azureml.core import Run
Run.get_environment()

To install a Conda environment as a kernel in a notebook, see add a new Jupyter kernel and the code should be followed in a same sequence:

conda create --name newenv
conda activate newenv
conda install pip
conda install ipykernel
python -m ipykernel install --user --name newenv --display-name "Python (newenv)"

To add, change or remove the Jupyter Kernels, please refer this article.

Refer this Document for more details

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alicia
Solution 2
Solution 3 Muhammad Murad Haider
Solution 4 Peter Mortensen
Solution 5 c z
Solution 6 DelliganeshS-MT