Home > OS >  powershell - split-path on string
powershell - split-path on string

Time:11-16

I have a variable called $path which has a value of

My Pictures/Tony/Automatic Upload/Tony’s iPhone/2022-11-13 10-57-52.mov

trying to use split-path to get just 2022-11-13 10-57-52.mov

Split-Path -Path $path -Leaf -Resolve               
Split-Path : Cannot find path 'C:\Users\Tony\My Pictures\Tony\Automatic Upload\Tony’s iPhone\2022-11-13 10-57-52.mov' because it does not exist.
At line:1 char:1
  Split-Path -Path $path -Leaf -Resolve
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : ObjectNotFound: (C:\Users\Tony\M...13 10-57-52.mov:String) [Split-Path], ItemNotFoundException
      FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SplitPathCommand

don't have it working yet... any guidance ?

CodePudding user response:

You can use the split in the following way:

$path = "My Pictures/Tony/Automatic Upload/Tony’s iPhone/2022-11-13 10-57-52.mov"
$file = $path.Split("/")[-1]
Write-Output $file

CodePudding user response:

If you don't care whether the file exists, you should use:

Split-Path -Leaf $path

If you ARE expecting the file to exist, then your problem is with the value in your $path variable.

My Pictures is a special folder, and the real path is not what you see in the Windows UI. You can see the real path with the following command, for example:

[Environment]::GetFolderPath('MyPictures')

Or right-click on the file to get its properties and view the real path there.

  • Related