Skip to content

Instantly share code, notes, and snippets.

@heiwa4126
Created October 23, 2020 01:09
Show Gist options
  • Select an option

  • Save heiwa4126/20a90112f50289d042a9a00b84717e59 to your computer and use it in GitHub Desktop.

Select an option

Save heiwa4126/20a90112f50289d042a9a00b84717e59 to your computer and use it in GitHub Desktop.
PowerShellでファイルかディレクトリか存在しないかを知る。 よくネットで見るのはPSIsContainerで識別する方法だけど、レジストリが来たら大惨事に (例: `HKCU:\`)。 知りたいのは **「ファイルシステム上のファイル(かディレクトリ)」** なのだ。
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# $ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
function isFileDir {
[OutputType([string])]
Param ([string]$file)
$i = Get-Item -LiteralPath $file -ErrorAction silent
if ($null -eq $i) {
return ("'{0}' does not exist." -f $file)
}
if ($i -is [System.IO.DirectoryInfo]) {
return ("'{0}' is directory." -f $file)
}
if ($i -is [System.IO.FileInfo]) {
return ("'{0}' is file." -f $file)
}
return ("'{0}' is not filesystem." -f $file)
}
# tests
isFileDir 'C:\'
isFileDir 'C:\notexists'
isFileDir 'C:\Windows\notepad.exe'
isFileDir 'HKCU:\'
isFileDir 'nul'
@heiwa4126
Copy link
Copy Markdown
Author

heiwa4126 commented Oct 23, 2020

LiteralPathにしてるのはglob避け。実行結果は

'C:\' is directory.
'C:\notexists' does not exist.
'C:\Windows\notepad.exe' is file.
'HKCU:\' is not filesystem.
'nul' does not exist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment