PowerShell: How to Convert String to Directory Object


You can use the following syntax in PowerShell to convert a string to a directory object:

$my_dir = Get-Item $my_string

This particular example converts the string stored in the variable named $my_string to a directory object with the variable name $my_dir.

This syntax assumes that the directory already exists. If the directory does not already exist, then you will receive an error.

If you’d like, you could use the following syntax to create the directory if it does not already exist:

if(Test-Path $my_string){
    $my_dir = Get-Item $my_string
} else{
    $my_dir = md $my_string
}

The following example shows how to use this syntax in practice.

Example: How to Convert String to Directory Object Using PowerShell

Suppose that we create a string variable with the following folder path in PowerShell:

  • “c:\users\bobbi\data1”

We can use the following syntax to create a string variable named $my_string that contains this folder path and then convert it to a directory object named $my_dir:

$my_string = "c:\users\bobbi\data1"
$my_dir = Get-Item $my_string 

The following screenshot shows how to use this syntax in practice:

PowerShell convert string to directory object

We can see that the string variable named $my_string has successfully been converted to a directory object named $my_dir.

Note that we were also able to use the syntax $my_dir.FullName to retrieve the full path to the directory.

Now suppose instead that we create a string variable with the following folder path:

  • “c:\users\bobbi\data100”

This directory currently doesn’t exist so if we attempt to use the Get-Item cmdlet to convert this string to a directory object then we will receive an error:

$my_string = "c:\users\bobbi\data100"
$my_dir = Get-Item $my_string

The following screenshot shows how to use this syntax in practice:

Notice that we receive an error because the directory specified by the string variable does not already exist.

We can use the following syntax instead to create this directory if it does not exist:

if(Test-Path $my_string){
    $my_dir = Get-Item $my_string
} else{
    $my_dir = md $my_string
}

The following screenshot shows how to use this syntax in practice:

Notice that we’re able to successfully convert the $my_string variable to a directory object named $my_dir.

Note that we were also able to use the syntax $my_dir.FullName to retrieve the full path to this newly created directory.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Convert String to Double
PowerShell: How to Convert String to Datetime
PowerShell: How to Convert Hash Table to String

Leave a Reply