Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
D.R. Avatar asked Oct 22 '15 12:10

D.R.


People also ask

How do I convert a string to an array in PowerShell?

Split() function. The . Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.

How do you change a datatype in PowerShell?

The rules for converting any value to type byte, int, or long are as follows: The bool value False is converted to zero; the bool value True is converted to 1. A char type value whose value can be represented in the destination type has that value; otherwise, the conversion is in error.

How do I convert a string to an int in PowerShell?

Use [int] to Convert String to Integer in PowerShell The data type of $a is an integer . But when you enclose the value with " " , the data type will become string . To convert such string data type to integer, you can use [int] as shown below.


2 Answers

Okay, the answer seems to be Get-Item:

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

Works!

like image 61
D.R. Avatar answered Oct 05 '22 09:10

D.R.


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

like image 25
Io-oI Avatar answered Oct 05 '22 09:10

Io-oI