简体   繁体   中英

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 $_ $myFileAsFile = $myFileAsStr | dir $_ , however, how to obtain my goal for a $directoryAsString ?

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.

Okay, the answer seems to be Get-Item :

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

Works!

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

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

$(Get-Item $directoryAsString).FullName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM