在PowerShell中将字符串转换为目录对象

flmtquvp  于 2023-03-30  发布在  Shell
关注(0)|答案(6)|浏览(161)

我从文件中逐行读取字符串(使用Get-Content和foreach循环),我想将这些字符串转换为目录对象(以便我可以访问.FullName等属性)。如何轻松地从字符串转换为目录?
使用文件很容易:$myFileAsFile = $myFileAsStr | dir $_,但是,如何获得我的目标为$directoryAsString

ui7jx7zq

ui7jx7zq1#

答案是Get-Item

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

管用!

falq053o

falq053o2#

您可以使用.Net类System.IO.FileInfoSystem.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的例子。

j8yoct9x

j8yoct9x3#

所以,从字符串类型变量获取路径/完整路径的简单方法,对我来说总是有效的:

(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
kupeojn6

kupeojn64#

Get-item将根据输入输出一个fileinfo或directoryinfo对象。或者管道到get-item -path { $_ }

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

j5fpnvbx5#

快捷方式

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

上面的工作,但容易受到错误的输入。所以,合并一些以前的评论和一点输入验证...

# 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

上面的是有点笨拙,所以,收紧的东西了...

  • 处理尾随“\”问题
  • 在FSO上使用.“GetType()”将指示允许特定处理的对象类型。
# 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
}
kyxcudwk

kyxcudwk6#

$(获取项目$目录为字符串).全名

相关问题