D.R.
D.R.

Reputation: 21194

Convert string to directory object in PowerShell

I read strings line by line from a file (using Get-Content and a foreach loop), I want to convert those strings to directory objects (so that I can access properties like .FullName). How to easily convert from string to directory?

With files it is easy: $myFileAsFile = $myFileAsStr | dir $_, however, how to obtain my goal for a $directoryAsString?

Upvotes: 21

Views: 37422

Answers (6)

AntGut
AntGut

Reputation: 81

The quick way

# "Get-Item" automatically grabs $Path item as an object if it exists.
# Carry on your merry way.
$FSO = Get-Item -Path $Path -Force

The above works but is susceptible to bad input. So, combine with some of the previous comments and a little input validation...

# Get path string (via parm, pipeline, etc.)
# Can be full path ('c:\users\Me') or properly formatted relative path ('..\..\Logs').
$Path = '<some_string>'

# Never presume the input actually exists, so check it with "Test-Path".
# Note: If the string is a file and ends with "\", this check will fail (generate an error).
# YMMV: add add'l code to strip off trailing "\" unless it's a drive (e.g., "C:\") prior to the check.
if (Test-Path $Path -PathType Leaf) {
    $PathType = 'File'
} elseif (Test-Path $Path -PathType Container) {
    $PathType = 'Folder'
} else {$PathType = $null}

# "Get-Item" automatically grabs item as an object if it exists.
if ($PathType) {
    $FSO = Get-Item -Path $Path -Force
    Write-Host 'Object is:' $PathType
    Write-Host 'FullName: ' $FSO.FullName
} else {
    Write-Host 'Bad path provided.'
    exit
}

# Some Test-Path samples:
$Path = 'c:\windows\'             # Folder: Test-Path works
$Path = 'c:\windows'              # Folder: Test-Path works
$Path = 'c:\windows\system.ini'   # File: Test-Path works
$Path = 'c:\windows\system.ini\'  # File: Test-Path FAILS
$Path = '..\system.ini'           # File: Test-Path works
$Path = '..\system.ini\'          # File: Test-Path FAILS

The above is kinda kludgy, so, tighten things up...

  • Handle the trailing "\" problem
  • Using ".GetType()" on a FSO will indicate the object type allowing for specific processing.
# Get path string (via parm, pipeline, etc.)
$Path = '<some_string>'

# Remove trailing "\" on all but drive paths (e.g., C:\, D:\)
if ($Path.EndsWith("\")) {
    if ($Path.Length -gt 3) {
        $Path = $Path.Remove($Path.Length - 1)
    }
}

# If the provided path exists, do stuff based on object type
# Else, go another direction as necessary
if (Test-Path -Path $Path) {
    $FSO = Get-Item -Path $Path -Force
    if ($FSO.GetType().FullName -eq "System.IO.DirectoryInfo") {
        Write-Host "Do directory stuff."
    } elseif ($FSO.GetType().FullName -eq "System.IO.FileInfo") {
        Write-Host "Do file stuff."
    } else {
         Write-Host "Valid path, but NOT a file system object!! (could be a registry item, etc.)"
    }
    Write-Host $FSO.FullName
} else {
    Write-Host "Path does not exist. Bail or do other processing, such as creating the path."
    $FSO = $null
}

Upvotes: 0

Io-oI
Io-oI

Reputation: 2565

So, the simple way for get path/full path from string type variable, that always works to me:

(Resolve-Path $some_string_var)

Set-Variable -Name "str_path_" -Value "G:\SO_en-EN\Q33281463\Q33281463.ps1"

$fullpath = (Resolve-Path $some_string_var) ; $fullpath

Upvotes: 6

js2010
js2010

Reputation: 27428

Get-item will output a fileinfo or directoryinfo object depending on the input. Or pipe to get-item -path { $_ }.

$myFileAsFile = get-item $myFileAsStr
$directoryAsDir = get-item $directoryAsString

Upvotes: 1

Phoenix14830
Phoenix14830

Reputation: 380

$(Get-Item $directoryAsString).FullName

Upvotes: -2

Mikhail Tumashenko
Mikhail Tumashenko

Reputation: 1723

You can use .Net class System.IO.FileInfo or System.IO.DirectoryInfo. This will work even if directory does not exist:

$c = [System.IO.DirectoryInfo]"C:\notexistentdir"
$c.FullName

It will even work with a file:

$c = [System.IO.DirectoryInfo]"C:\some\file.txt"
$c.Extension

So to check if it is really a directory use:

$c.Attributes.HasFlag([System.IO.FileAttributes]::Directory)

There's an example with System.IO.FileInfo in the comment below.

Upvotes: 23

D.R.
D.R.

Reputation: 21194

Okay, the answer seems to be Get-Item:

$dirAsStr = '.\Documents'
$dirAsDir = Get-Item $dirAsStr
echo $dirAsDir.FullName

Works!

Upvotes: 27

Related Questions