Windows powershell if exist

Test-Path

Determines whether all elements of a path exist.

Syntax

Description

The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element. If the Path is whitespace an empty string, then $False is returned. If the Path is $null , array of $null or empty array, a non-terminating error is returned.

Examples

Example 1: Test a path

This command checks whether all elements in the path exist, that is, the C: directory, the Documents and Settings directory, and the DavidC directory. If any are missing, the cmdlet returns $False . Otherwise, it returns $True .

Example 2: Test the path of a profile

These commands test the path of the PowerShell profile.

The first command determines whether all elements in the path exist. The second command determines whether the syntax of the path is correct. In this case, the path is $False , but the syntax is correct $True . These commands use $profile , the automatic variable that points to the location for the profile, even if the profile does not exist.

For more information about automatic variables, see about_Automatic_Variables.

Example 3: Check whether there are any files besides a specified type

This command checks whether there are any files in the Commercial Buildings directory other than .dwg files.

The command uses the Path parameter to specify the path. Because the path includes a space, the path is enclosed in quotation marks. The asterisk at the end of the path indicates the contents of the Commercial Building directory. With long paths, such as this one, type the first few letters of the path, and then use the TAB key to complete the path.

The command specifies the Exclude parameter to specify files that will be omitted from the evaluation.

In this case, because the directory contains only .dwg files, the result is $False .

Example 4: Check for a file

This command checks whether the path stored in the $profile variable leads to a file. In this case, because the PowerShell profile is a .ps1 file, the cmdlet returns $True .

Читайте также:  Intel hd 405 linux

Example 5: Check paths in the Registry

These commands use Test-Path with the PowerShell registry provider.

The first command tests whether the registry path of the Microsoft.PowerShell registry key is correct on the system. If PowerShell is installed correctly, the cmdlet returns $True .

Test-Path does not work correctly with all PowerShell providers. For example, you can use Test-Path to test the path of a registry key, but if you use it to test the path of a registry entry, it always returns $False , even if the registry entry is present.

Example 6: Test if a file is newer than a specified date

This command uses the NewerThan dynamic parameter to determine whether the «PowerShell.exe» file on the computer is newer than «July 13, 2009».

The NewerThan parameter works only in file system drives.

Example 7: Test a path with null as the value

The error returned for null , array of null or empty array is a non-terminating error. It can be suppress by using -ErrorAction SilentlyContinue . The following example shows all cases which return the NullPathNotPermitted error.

Example 8: Test a path with whitespace as the value

When a whitespace or empty string is provided for the the -Path parameter, it returns False. The following example show whitespace and empty string.

Parameters

This parameter is not supported by any providers installed with PowerShell. To impersonate another user, or elevate your credentials when running this cmdlet, use Invoke-Command.

Type: PSCredential
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specifies items that this cmdlet omits. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as «*.txt». Wildcard characters are permitted.

Type: String [ ]
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: True

Specifies a filter in the format or language of the provider. The value of this parameter qualifies the Path parameter. The syntax of the filter, including the use of wildcard characters, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when it retrieves the objects instead of having PowerShell filter the objects after they are retrieved.

Type: String
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: True

Specifies paths that this cmdlet tests. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as «*.txt». Wildcard characters are permitted.

Type: String [ ]
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: True

Indicates that this cmdlet tests the syntax of the path, regardless of whether the elements of the path exist. This cmdlet returns $True if the path syntax is valid and $False if it is not.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies a path to be tested. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes characters that could be interpreted by PowerShell as escape sequences, you must enclose the path in single quote so that they won’t be interpreted.

Читайте также:  Autocad mac os требования
Type: String [ ]
Aliases: PSPath, LP
Position: Named
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Specify a time as a DateTime object.

Type: Nullable [ DateTime ]
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specify a time as a DateTime object.

Type: Nullable [ DateTime ]
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies a path to be tested. Wildcard characters are permitted. If the path includes spaces, enclose it in quotation marks.

Type: String [ ]
Position: 0
Default value: None
Accept pipeline input: True
Accept wildcard characters: True

Specifies the type of the final element in the path. This cmdlet returns $True if the element is of the specified type and $False if it is not. The acceptable values for this parameter are:

  • Container. An element that contains other elements, such as a directory or registry key.
  • Leaf. An element that does not contain other elements, such as a file.
  • Any. Either a container or a leaf.

Tells whether the final element in the path is of a particular type.

Up to PowerShell version 6.1.2, when the IsValid and PathType switches are specified together, the Test-Path cmdlet ignores the PathType switch and only validates the syntactic path without validating the path type.

According to issue #8607, fixing this behavior may be a breaking change in a future version, where the IsValid and PathType switches belong to separate parameter sets, and thus, cannot be used together avoiding this confusion.

Type: TestPathType
Aliases: Type
Accepted values: Any, Container, Leaf
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Inputs

You can pipe a string that contains a path, but not a literal path, to this cmdlet.

Outputs

The cmdlet returns a Boolean value.

Notes

The cmdlets that contain the Path noun (the Path cmdlets) work with path names and return the names in a concise format that all PowerShell providers can interpret. They are designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them as you would use Dirname, Normpath, Realpath, Join, or other path manipulators.

The Test-Path is designed to work with the data exposed by any provider. To list the providers available in your session, type Get-PSProvider . For more information, see about_Providers.

Check if File Exists with Powershell

It’s very easy to check if a file exists with Powershell and take an action if so, here are some examples:

Check if a file exists

Delete file if it exists

An even shorter method….

Check if a file exists and get the content

Check if a file exists and print a message if it does or does not exist

Check if a file exists and show the properties of the file

Check if a file exists and move it to a new location

It’s obvious from the above examples that Test-Path simply returns a Boolean (i.e. True or False) and executing it on its own will produce exactly that:

The PathType parameter is not strictly required, but it is useful if you want to be sure the check you are performing is actually a file, not a directory.

Читайте также:  Разгрузка процессора windows 10

You can check for a directory by setting PathType to “container”

Filed Under: How To Tagged With: Powershell

Reader Interactions

Comments

Hi
Nice, is there a command to check the content of a file ? I download a file and at the end of this file is the command: Copying finished
I would like to have an email sent, when this command appears, is it possible ?

Thanks for help

Trackbacks

[…] Now that you know how to check for a file in VBScript, read up on how to check if a file exists with Powershell. […]

Powershell check if folder exists

In this little article I describe how to use the cmdlet Test-Path to check if a folder exists. Type Get-Help Test-Path for built-in information. I also briefly demonstrate how to use the .NET class method Exists() from the class System.IO.Directory.

Contents

How To Check If A Folder Exists With PowerShell

You can use something like this for verification on the command line:

Remember that you need single or double quotes around the path if it contains a space. Single quotes are recommended, since they don’t expand/substitute/interpolate variables.

To explicitly make sure it’s a directory and not a file, use the -PathType parameter which accepts the following values:

Screenshot Example

Script Usage

In a script, you would typically use it in an if statement. To negate and check if the folder or file does not exist, use either «!» or «-not», and remember to enclose the Test-Path statement in parentheses.

Also remember that if the path or folder name contains a space, you need to surround the entire path in quotes. Single quotes or double quotes will work the same if there are no «expandable» parts in the path or folder name, but the slightly safer choice is single quotes. This is what PowerShell defaults to when you auto-complete names with tab at the prompt.

You should also be made aware of the parameter -LiteralPath to Test-Path, that you can see in the second example above. This also works if your file contains characters like brackets that causes the -Path parameter to expand the path since it supports wildcard syntax by default. Use -LiteralPath if you don’t need expansion from -Path as it’s the safer choice for oddly named files.

Create A Directory If It Does Not Exist

To create a directory if it does not exist, this is a very robust example of how you might want to handle it. Adapt to suit your needs.

This code was put in the file «NewDirDemo.ps1» that you see me using below.

Demonstration of use in the following screenshot.

Enumerating Possible PathType Values

A small «trick» to see the possible enumeration values for -PathType is to use one that doesn’t exist, like this:

Using The .NET System.IO.Directory Class Method «Exists»

You can also use the Exists() method from the .NET System.IO.Directory class, which requires a full path:

If you want to check if the directory the script/program is currently in contains a subdirectory, you can use the trick I demonstrate below — where I check if there’s a subdirectory called «Windows».

In PowerShell, the namespace «System» doesn’t have to be typed in explicitly, so you can omit it.

Оцените статью