program story

PowerShell의 파일 이름에서 경로 및 확장자 제거

inputbox 2020. 9. 15. 07:46
반응형

PowerShell의 파일 이름에서 경로 및 확장자 제거


파일에 대한 전체 경로 인 일련의 문자열이 있습니다. 파일 확장자와 선행 경로없이 파일 이름 만 저장하고 싶습니다. 그래서 이것으로부터 :

c:\temp\myfile.txt

myfile

나는 실제로 디렉토리를 반복하는 것이 아니라 powershell의 basename속성 과 같은 것을 사용할 수있는 경우가 아니라 문자열 만 처리합니다.


이를위한 편리한 .NET 메서드가 있습니다.

C:\PS> [io.path]::GetFileNameWithoutExtension("c:\temp\myfile.txt")
myfile

전체 경로, 디렉토리, 파일 이름 또는 파일 확장자를 표시하는 문제를 해결하기 위해 생각했던 것보다 훨씬 쉽습니다.

$PSCommandPath
(Get-Item $PSCommandPath ).Extension
(Get-Item $PSCommandPath ).Basename
(Get-Item $PSCommandPath ).Name
(Get-Item $PSCommandPath ).DirectoryName
(Get-Item $PSCommandPath ).FullName
$ConfigINI = (Get-Item $PSCommandPath ).DirectoryName+"\"+(Get-Item $PSCommandPath ).BaseName+".ini"
$ConfigINI

다른 형태 :

$scriptPath = split-path -parent $MyInvocationMyCommand.Definition
split-path -parent $PSCommandPath
Split-Path $script:MyInvocation.MyCommand.Path
split-path -parent $MyInvocation.MyCommand.Definition
[io.path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)

@ walid2mi 답변 에서 영감을 얻었 습니다.

(Get-Item 'c:\temp\myfile.txt').Basename

참고 : 이것은 주어진 파일이 실제로 존재하는 경우에만 작동 합니다 .


또는

([io.fileinfo]"c:\temp\myfile.txt").basename

또는

"c:\temp\myfile.txt".split('\.')[-2]

basename 속성을 사용할 수 있습니다.

PS II> ls *.ps1 | select basename

@Keith ,

여기에 또 다른 옵션 :

PS II> $f="C:\Downloads\ReSharperSetup.7.0.97.60.msi"

PS II> $f.split('\')[-1] -replace '\.\w+$'

PS II> $f.Substring(0,$f.LastIndexOf('.')).split('\')[-1]

임의의 경로 문자열이 주어지면 System.IO.Path 개체에 대한 다양한 정적 메서드는 다음과 같은 결과를 제공합니다.

strTestPath = C : \ Users \ DAG \ Documents \ Articles_2018 \ NTFS_File_Times_in_CMD \ PathStringInfo.ps1
GetDirectoryName = C : \ Users \ DAG \ Documents \ Articles_2018 \ NTFS_File_Times_in_CMD
GetFileName = PathStringInfo.ps1
GetExtension = .ps1
GetFileNameWithoutExtension = PathStringInfo

다음은 위의 출력을 생성 한 코드입니다.

[console]::Writeline( "strTestPath                 = {0}{1}" ,
                      $strTestPath , [Environment]::NewLine );
[console]::Writeline( "GetDirectoryName            = {0}" ,
                      [IO.Path]::GetDirectoryName( $strTestPath ) );
[console]::Writeline( "GetFileName                 = {0}" ,
                      [IO.Path]::GetFileName( $strTestPath ) );
[console]::Writeline( "GetExtension                = {0}" ,
                      [IO.Path]::GetExtension( $strTestPath ) );
[console]::Writeline( "GetFileNameWithoutExtension = {0}" ,
                      [IO.Path]::GetFileNameWithoutExtension( $strTestPath ) );

위의 스크립트를 작성하고 테스트 한 결과 PowerShell이 ​​C #, C, C ++, Windows NT 명령 스크립팅 언어 및 경험이있는 다른 모든 것과 어떻게 다른지에 대한 몇 가지 단점이 발견되었습니다.


여기에 괄호가없는 것이 있습니다.

[io.fileinfo] 'c:\temp\myfile.txt' | % basename

이것은 문자열을 몇 번 분할하여 수행 할 수 있습니다.

#Path
$Link = "http://some.url/some/path/file.name"

#Split path on "/"
#Results of split will look like this : 
# http:
#
# some.url
# some
# path
# file.name
$Split = $Link.Split("/")

#Count how many Split strings there are
#There are 6 strings that have been split in my example
$SplitCount = $Split.Count

#Select the last string
#Result of this selection : 
# file.name
$FilenameWithExtension = $Split[$SplitCount -1]

#Split filename on "."
#Result of this split : 
# file
# name
$FilenameWithExtensionSplit = $FilenameWithExtension.Split(".")

#Select the first half
#Result of this selection : 
# file
$FilenameWithoutExtension = $FilenameWithExtensionSplit[0]

#The filename without extension is in this variable now
# file
$FilenameWithoutExtension

Here is the code without comments :

$Link = "http://some.url/some/path/file.name"
$Split = $Link.Split("/")
$SplitCount = $Split.Count
$FilenameWithExtension = $Split[$SplitCount -1]
$FilenameWithExtensionSplit = $FilenameWithExtension.Split(".")
$FilenameWithoutExtension = $FilenameWithExtensionSplit[0]
$FilenameWithoutExtension

참고URL : https://stackoverflow.com/questions/12503871/removing-path-and-extension-from-filename-in-powershell

반응형