简体   繁体   中英

How to replace a string in powershell?

I need to extricate the file extension from the file paths. For Eg: I have a file path like:

\\Test\data\data.dll

How to remove the data.dll from the file path, so that I get only

\\Test\data\

as the output.

I tried using the wild character - *. but that didn't work.

Thanks!

In your case there is a special cmdlet that by default removes the file or folder at the end. Try:

$path =  \\test\data\data.dll
#Get folderpath    
Split-Path $path
#Get filename only (thanks to Christian for tip)
Split-Path $path -Leaf

Here's 2 different ways of doing it. One is to use Split-Path. The other is to use -replace with regular expressions. They both work great in PowerShell V3, but Split-Path doesn't work in V2 if the path has a drive letter in it, but your system doesn't have that drive letter.

#Get Folder
Split-Path '\\test\data\data.dll'
'\\test\data\data.dll' -replace '\\[^\\]+$'

#Get File 
Split-Path '\\test\data\data.dll' -Leaf
'\\test\data\data.dll' -replace '^\\.*\\'

Just to add my 2 cents for a workaround for the issue told by @StephenMills in his answer:

PS C:\ps> ( [system.io.fileinfo]"J:\data\data.dll" ).FullName
J:\data\data.dll
PS C:\ps> ( [system.io.fileinfo]"J:\data\data.dll" ).BaseName
data
PS C:\ps> ( [system.io.fileinfo]"J:\data\data.dll" ).name
data.dll
PS C:\ps> ( [system.io.fileinfo]"J:\data\data.dll" ).DirectoryName
J:\data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM