在 PowerShell 中将字符串转换为目录对象
Convert string to directory object in PowerShell
我从文件中逐行读取字符串(使用 Get-Content 和 foreach 循环),我想将这些字符串转换为目录对象(以便我可以访问 .FullName
等属性)。如何轻松地将字符串转换为目录?
使用文件很容易:$myFileAsFile = $myFileAsStr | dir $_
,但是,如何获得我的 $directoryAsString
目标?
好吧,答案好像是Get-Item
:
$dirAsStr = '.\Documents'
$dirAsDir = Get-Item $dirAsStr
echo $dirAsDir.FullName
有效!
您可以使用 .Net class System.IO.FileInfo
或 System.IO.DirectoryInfo
。即使目录不存在,这也会起作用:
$c = [System.IO.DirectoryInfo]"C:\notexistentdir"
$c.FullName
它甚至可以处理一个文件:
$c = [System.IO.DirectoryInfo]"C:\some\file.txt"
$c.Extension
所以要检查它是否真的是目录,请使用:
$c.Attributes.HasFlag([System.IO.FileAttributes]::Directory)
下面的评论中有一个 System.IO.FileInfo
的例子。
$(获取项目 $directoryAsString).FullName
因此,从字符串类型变量获取 path/full 路径的简单方法对我来说总是有效:
(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 将根据输入输出文件信息或目录信息对象。或者通过管道传输到 get-item -path { $_ }
.
$myFileAsFile = get-item $myFileAsStr
$directoryAsDir = get-item $directoryAsString
我从文件中逐行读取字符串(使用 Get-Content 和 foreach 循环),我想将这些字符串转换为目录对象(以便我可以访问 .FullName
等属性)。如何轻松地将字符串转换为目录?
使用文件很容易:$myFileAsFile = $myFileAsStr | dir $_
,但是,如何获得我的 $directoryAsString
目标?
好吧,答案好像是Get-Item
:
$dirAsStr = '.\Documents'
$dirAsDir = Get-Item $dirAsStr
echo $dirAsDir.FullName
有效!
您可以使用 .Net class System.IO.FileInfo
或 System.IO.DirectoryInfo
。即使目录不存在,这也会起作用:
$c = [System.IO.DirectoryInfo]"C:\notexistentdir"
$c.FullName
它甚至可以处理一个文件:
$c = [System.IO.DirectoryInfo]"C:\some\file.txt"
$c.Extension
所以要检查它是否真的是目录,请使用:
$c.Attributes.HasFlag([System.IO.FileAttributes]::Directory)
下面的评论中有一个 System.IO.FileInfo
的例子。
$(获取项目 $directoryAsString).FullName
因此,从字符串类型变量获取 path/full 路径的简单方法对我来说总是有效:
(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 将根据输入输出文件信息或目录信息对象。或者通过管道传输到 get-item -path { $_ }
.
$myFileAsFile = get-item $myFileAsStr
$directoryAsDir = get-item $directoryAsString