# "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
}
6条答案
按热度按时间ui7jx7zq1#
答案是
Get-Item
:管用!
falq053o2#
您可以使用.Net类
System.IO.FileInfo
或System.IO.DirectoryInfo
。即使目录不存在,这也可以工作:它甚至可以处理一个文件:
因此,要检查它是否真的是一个目录,请使用:
下面的评论中有一个
System.IO.FileInfo
的例子。j8yoct9x3#
所以,从字符串类型变量获取路径/完整路径的简单方法,对我来说总是有效的:
kupeojn64#
Get-item将根据输入输出一个fileinfo或directoryinfo对象。或者管道到
get-item -path { $_ }
。j5fpnvbx5#
快捷方式
上面的工作,但容易受到错误的输入。所以,合并一些以前的评论和一点输入验证...
上面的是有点笨拙,所以,收紧的东西了...
kyxcudwk6#
$(获取项目$目录为字符串).全名