How to get the Parent's parent directory in Powershell? - powershell

So if I have a directory stored in a variable, say:
$scriptPath = (Get-ScriptDirectory);
Now I would like to find the directory two parent levels up.
I need a nice way of doing:
$parentPath = Split-Path -parent $scriptPath
$rootPath = Split-Path -parent $parentPath
Can I get to the rootPath in one line of code?

Version for a directory
get-item is your friendly helping hand here.
(get-item $scriptPath ).parent.parent
If you Want the string only
(get-item $scriptPath ).parent.parent.FullName
Version for a file
If $scriptPath points to a file then you have to call Directory property on it first, so the call would look like this
(get-item $scriptPath).Directory.Parent.Parent.FullName
Remarks
This will only work if $scriptPath exists. Otherwise you have to use Split-Path cmdlet.

I've solved that like this:
$RootPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

You can split it at the backslashes, and take the next-to-last one with negative array indexing to get just the grandparent directory name.
($scriptpath -split '\\')[-2]
You have to double the backslash to escape it in the regex.
To get the entire path:
($path -split '\\')[0..(($path -split '\\').count -2)] -join '\'
And, looking at the parameters for split-path, it takes the path as pipeline input, so:
$rootpath = $scriptpath | split-path -parent | split-path -parent

You can use
(get-item $scriptPath).Directoryname
to get the string path or if you want the Directory type use:
(get-item $scriptPath).Directory

You can simply chain as many split-path as you need:
$rootPath = $scriptPath | split-path | split-path

simplest solution
Here's the simplest solution
"$path\..\.."
If you want to get an absolute path, you can
"$path\..\.." | Convert-Path
reusable solution
Here is a reusable solution, first define the getParent function, then call it directly.
function getParent($path, [int]$deep = 1) {
$result = $path | Get-Item | ForEach-Object { $_.PSIsContainer ? $_.Parent : $_.Directory }
for ($deep--; $deep -gt 0; $deep--) { $result = getParent $result }
return $result
}
getParent $scriptPath 2

In PowerShell 3, $PsScriptRoot or for your question of two parents up,
$dir = ls "$PsScriptRoot\..\.."

Split-Path -Path (Get-Location).Path -Parent

To extrapolate a bit on the other answers (in as Beginner-friendly a way as possible):
String objects that point to valid paths can be converted to DirectoryInfo/FileInfo objects via functions like Get-Item and Get-ChildItem.
.Parent can only be used on a DirectoryInfo object.
.Directory converts a FileInfo object to a DirectoryInfo object (targeting the file's directory), and will return null if used on any other type (even another DirectoryInfo object).
.DirectoryName converts a FileInfo object to a String object (targeting the file's directory), and will return null if used on any other type (even another String object).
.FullName converts a DirectoryInfo/FileInfo object to a String object, and will return null if used on any other type (even another DirectoryInfo/FileInfo object).
.Path converts a PathInfo object to a String object, and will return null if used on any other type (even another PathInfo object).
Check the object type with the GetType Method to see what you're working with: $scriptPath.GetType()
Lastly, a quick tip that helps with making one-liners: Get-Item has the gi alias and Get-ChildItem has the gci alias.

If you want to use $PSScriptRoot you can do
Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve

In powershell :
$this_script_path = $(Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
$parent_folder = Split-Path $this_script_path -Leaf

Related

How to run command for several files in PowerShell

I have a folder with images and I need to convert them using ImageMagick . How to run command for each file (as parameter) in Powershell?
For efficiency's sake (since I can see you're on v4 by your use of the array ForEach method), you can use the -File switch on Get-ChildItem (introduced in v3) and only get the files you need. Additionally, using the foreach keyword is more readable and performant than either .ForEach() or ForEach-Object.
You can use the call operator to run external executables (&):
$magick = 'C:\INSTALL\ImageMagick-7.0.8-Q16\magick.exe'
$path = 'C:\Pictres'
foreach ($file in Get-ChildItem -Path $path -File) {
& $magick "$($file.FullName)" -negate "$path\test_$($file.Name)"
}
The Get-ChildItem returns an array of FileInfo objects and you should not treat them as simply string that hold the path and file name.
Instead, use the properties of these objects FullName and Name
Get-ChildItem -Path "C:\Pictres" -File | ForEach-Object {
# The automatic variable '$_' or '$PSItem' contains the current object in the PowerShell pipeline.
$originalImage = $_.FullName
$convertedImage = Join-Path -Path $_.DirectoryName -ChildPath ('test_{0}' -f $_.Name)
& 'C:\INSTALL\ImageMagick-7.0.8-Q16\magick.exe' "$originalImage" -negate "$convertedImage"
}
Use Get-ChildItem and ForEach. $PSItem is defined automatically
(Get-ChildItem -Path "C:\Pictres").ForEach({
>> $BuildName = "C:\Pictres\$PSItem"
>> $BuildName2 = "C:\Pictres\test_$PSItem"
>> C:\INSTALL\ImageMagick-7.0.8-Q16\magick.exe "$BuildName" -negate "$BuildName2"
>> }
>> )

Get a specific folder name from path

How to get the 4th folder name and store it in a variable while looping through the files stored in a parent folder. For example, if the path is
C:\ParentFolder\Subfolder1\subfolder2\subfolder3\file.extension
C:\ParentFolder\Subfolder1\subfolder2\subfolder4\file.extension
C:\ParentFolder\Subfolder1\subfolder2\subfolder5\file.extension
then subfolder2 name should be stored in a variable. Can any one please help me on this?
get-childitem $DirectorNane -Recurse | Where-Object{!($_.PSIsContainer)} | % {
$filePath = $_.FullName
#Get file name
$fileName = Split-Path -Path $filePath -Leaf
} $FileI = Split-Path -Path $filePath -Leaf
Thanks in advance!
You can use the -split operator on the $filePath variable to get what you want.
$split = $filePath -split '\\'
$myvar = $split[3]
We use the double backslash to split with, because the first slash escapes the slash character to split the path by. Then, we can reference the part of the path we want in the array that gets generated in the "split" variable.
Additionally, you can solve this with a one liner using the following code:
$myvar = $filepath.split('\')[3]
This would ensure that you're always getting the fourth element in the array, but is a little less flexible since you can't specify what exactly you want based on conditions with additional scripting.
If you are asking how to get the parent directory of the directory containing a file, you can call Split-Path twice. Example:
$filePath = "C:\ParentFolder\Subfolder1\subfolder2\subfolder3\file.extension"
$parentOfParent = Split-Path (Split-Path $filePath)
# $parentOfParent now contains "C:\ParentFolder\Subfolder1\subfolder2"

In PowerShell, how can I test if a user-supplied string represents a full absolute path? [duplicate]

I'm trying to process a list of files that may or may not be up to date and may or may not yet exist. In doing so, I need to resolve the full path of an item, even though the item may be specified with relative paths. However, Resolve-Path prints an error when used with a non-existant file.
For example, What's the simplest, cleanest way to resolve ".\newdir\newfile.txt" to "C:\Current\Working\Directory\newdir\newfile.txt" in Powershell?
Note that System.IO.Path's static method use with the process's working directory - which isn't the powershell current location.
You want:
c:\path\exists\> $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath(".\nonexist\foo.txt")
returns:
c:\path\exists\nonexists\foo.txt
This has the advantage of working with PSPaths, not native filesystem paths. A PSPath may not map 1-1 to a filesystem path, for example if you mount a psdrive with a multi-letter drive name.
What's a pspath?
ps c:\> new-psdrive temp filesystem c:\temp
...
ps c:\> cd temp:
ps temp:\>
temp:\ is a drive-qualified pspath that maps to a win32 (native) path of c:\temp.
-Oisin
When Resolve-Path fails due to the file not existing, the fully resolved path is accessible from the thrown error object.
You can use a function like the following to fix Resolve-Path and make it work like you expect.
function Force-Resolve-Path {
<#
.SYNOPSIS
Calls Resolve-Path but works for files that don't exist.
.REMARKS
From http://devhawk.net/blog/2010/1/22/fixing-powershells-busted-resolve-path-cmdlet
#>
param (
[string] $FileName
)
$FileName = Resolve-Path $FileName -ErrorAction SilentlyContinue `
-ErrorVariable _frperror
if (-not($FileName)) {
$FileName = $_frperror[0].TargetObject
}
return $FileName
}
I think you're on the right path. Just use [Environment]::CurrentDirectory to set .NET's notion of the process's current dir e.g.:
[Environment]::CurrentDirectory = $pwd
[IO.Path]::GetFullPath(".\xyz")
Join-Path (Resolve-Path .) newdir\newfile.txt
This has the advantage of not having to set the CLR Environment's current directory:
[IO.Path]::Combine($pwd,"non\existing\path")
NOTE
This is not functionally equivalent to x0n's answer. System.IO.Path.Combine only combines string path segments. Its main utility is keeping the developer from having to worry about slashes. GetUnresolvedProviderPathFromPSPath will traverse the input path relative to the present working directory, according to the .'s and ..'s.
I've found that the following works well enough.
$workingDirectory = Convert-Path (Resolve-Path -path ".")
$newFile = "newDir\newFile.txt"
Do-Something-With "$workingDirectory\$newFile"
Convert-Path can be used to get the path as a string, although this is not always the case. See this entry on COnvert-Path for more details.
function Get-FullName()
{
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline = $True)] [object[]] $Path
)
Begin{
$Path = #($Path);
}
Process{
foreach($p in $Path)
{
if($p -eq $null -or $p -match '^\s*$'){$p = [IO.Path]::GetFullPath(".");}
elseif($p -is [System.IO.FileInfo]){$p = $p.FullName;}
else{$p = [IO.Path]::GetFullPath($p);}
$p;
}
}
}
I ended up with this code in my case. I needed to create a file later in the the script, so this code presumes you have write access to the target folder.
$File = ".\newdir\newfile.txt"
If (Test-Path $File) {
$Resolved = (Resolve-Path $File).Path
} else {
New-Item $File -ItemType File | Out-Null
$Resolved = (Resolve-Path $File).Path
Remove-Item $File
}
I also enclosed New-Item in try..catch block, but that goes out of this question.
I had a similar issue where I needed to find the folder 3 levels up from a folder that does not exist yet to determine the name for a new folder I wanted to create... It's complicated. Anyway, this is what I ended up doing:
($path -split "\\" | select -SkipLast 3) -join "\\"
You can just set the -errorAction to "SilentlyContinue" and use Resolve-Path
5 > (Resolve-Path .\AllFilerData.xml -ea 0).Path
C:\Users\Andy.Schneider\Documents\WindowsPowerShell\Scripts\AllFilerData.xml
6 > (Resolve-Path .\DoesNotExist -ea 0).Path
7 >
There is an accepted answer here, but it is quite lengthy and there is a simpler alternative available.
In any recent version of Powershell, you can use Test-Path -IsValid -Path 'C:\Probably Fake\Path.txt'
This simply verifies that there are no illegal characters in the path and that the path could be used to store a file. If the target doesn't exist, Test-Path won't care in this instance -- it's only being asked to test if the provided path is potentially valid.
Both most popular answers don't work correctly on paths on not existing drives.
function NormalizePath($filename)
{
$filename += '\'
$filename = $filename -replace '\\(\.?\\)+','\'
while ($filename -match '\\([^\\.]|\.[^\\.]|\.\.[^\\])[^\\]*\\\.\.\\') {
$filename = $filename -replace '\\([^\\.]|\.[^\\.]|\.\.[^\\])[^\\]*\\\.\.\\','\'
}
return $filename.TrimEnd('\')
}
Check if the file exists before resolving:
if(Test-Path .\newdir\newfile.txt) { (Resolve-Path .\newdir\newfile.txt).Path }

How to convert absolute path to relative path in PowerShell?

I'd like to convert a path to a relative path in a PowerShell script.
How do I do this using PowerShell?
For example:
Path to convert: c:\documents\mynicefiles\afile.txt
Reference path: c:\documents
Result: mynicefiles\afile.txt
And
Path to convert: c:\documents\myproject1\afile.txt
Reference path: c:\documents\myproject2
Result: ..\myproject1\afile.txt
I found something built in, Resolve-Path:
Resolve-Path -Relative
This returns the path relative to the current location. A simple usage:
$root = "C:\Users\Dave\"
$current = "C:\Users\Dave\Documents\"
$tmp = Get-Location
Set-Location $root
Resolve-Path -relative $current
Set-Location $tmp
Using the built-in System.IO.Path.GetRelativePath is simpler than the accepted answer:
[System.IO.Path]::GetRelativePath($relativeTo, $path)
There is a good answer here, but it changes your current directory (it reverts back), but if you really need to isolate that process, code example below can help. It does the same thing, just in a new PowerShell instance.
function Get-RelativePath($path, $relativeTo) {
$powershell = (Get-Process -PID $PID | Get-Item)
if ([string]::IsNullOrEmpty($powershell)) {
$powershell = "powershell.exe"
}
& $powershell -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "& { Set-Location `"$relativeTo`"; Resolve-Path `"$path`" -Relative}"
}
It's really slow though, you should really use the other version unless you absolutely have to use this.
Sometimes I have multiple "roots" from which I want to generate relative file paths. I have found Resolve-Path -Relative unusable in this kind of situation. Changing a global setting, current location, in order to generate a relative file path seems error-prone and (if you're writing parallel code) possibly not thread-safe.
The following should work in early or recent versions of Powershell and Powershell Core, doesn't change your current directory, even temporarily, and is OS-independent and thread-safe.
It doesn't address the second example from OP (inserting .. as required.)
function Get-RelativePath {
param($path, $relativeTo)
# strip trailing slash
$relativeTo = Join-Path `
(Split-Path -Parent $relativeTo) `
(Split-Path -Leaf $relativeTo)
$relPath = Split-Path -Leaf $path
$path = Split-Path -Parent $path
do {
$leaf = Split-Path -Leaf $path
$relPath = Join-Path $leaf $relPath
$path = Split-Path -Parent $path
} until (($path -eq $relativeTo) -Or ($path.Length -eq 0))
$relPath
}
An example:
PS> $configRoot = 'C:\Users\P799634t\code\RMP\v2\AWD'
PS> $queryPath = 'C:\Users\P799634t\code\RMP\v2\AWD\config_queries\LOAD_UNQ_QUEUE_QUERY2.sql'
PS> Write-Host (Get-RelativePath $queryPath $configRoot)
config_queries\LOAD_UNQ_QUEUE_QUERY2.sql
It behaves reasonably when one file path is not a sub-path of the other:
PS> $root = 'C:\Users\P799634t\code\RMP\v2\AWD'
PS> $notRelated = 'E:\path\to\origami'
PS> Write-Host (Get-RelativePath $notRelated $root)
E:\path\to\origami
A quick and easy way would be :
$current -replace [regex]::Escape($root), '.'
Or if you want the relative path from your actual current location
$path -replace [regex]::Escape((pwd).Path), '.'
This assumes all your paths are valid.
Here is an alternative approach
$pathToConvert1 = "c:\documents\mynicefiles\afile.txt"
$referencePath1 = "c:\documents"
$result1 = $pathToConvert1.Substring($referencePath1.Length + 1)
#$result1: mynicefiles\afile.txt
And
$pathToConvert2 = "c:\documents\myproject1\afile.txt"
#$referencePath2 = "c:\documents\myproject2"
$result2 = "..\myproject" + [regex]::Replace($pathToConvert2 , ".*\d+", '')
#$result2: ..\myproject\afile.txt
Note: in the second case ref path wasn't used.

Removing path and extension from filename in PowerShell

I have a series of strings which are full paths to files. I'd like to save just the filename, without the file extension and the leading path. So from this:
c:\temp\myfile.txt
to
myfile
I'm not actually iterating through a directory, in which case something like PowerShell's basename property could be used, but rather I'm dealing with strings alone.
Way easier than I thought to address the issue of displaying the full path, directory, file name or file extension.
## Output:
$PSCommandPath ## C:\Users\user\Documents\code\ps\test.ps1
(Get-Item $PSCommandPath ).Extension ## .ps1
(Get-Item $PSCommandPath ).Basename ## test
(Get-Item $PSCommandPath ).Name ## test.ps1
(Get-Item $PSCommandPath ).DirectoryName ## C:\Users\user\Documents\code\ps
(Get-Item $PSCommandPath ).FullName ## C:\Users\user\Documents\code\ps\test.ps1
$ConfigINI = (Get-Item $PSCommandPath ).DirectoryName+"\"+(Get-Item $PSCommandPath ).BaseName+".ini"
$ConfigINI ## C:\Users\user\Documents\code\ps\test.ini
Other forms:
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
split-path -parent $PSCommandPath
Split-Path $script:MyInvocation.MyCommand.Path
split-path -parent $MyInvocation.MyCommand.Definition
[io.path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)
There's a handy .NET method for that:
C:\PS> [io.path]::GetFileNameWithoutExtension("c:\temp\myfile.txt")
myfile
Inspired by an answer of #walid2mi:
(Get-Item 'c:\temp\myfile.txt').Basename
Please note: this only works if the given file really exists.
or
([io.fileinfo]"c:\temp\myfile.txt").basename
or
"c:\temp\myfile.txt".split('\.')[-2]
you can use basename property
PS II> ls *.ps1 | select basename
Starting with PowerShell 6, you get the filename without extension like so:
split-path c:\temp\myfile.txt -leafBase
#Keith,
here another option:
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]
Expanding on René Nyffenegger's answer, for those who do not have access to PowerShell version 6.x, we use Split Path, which doesn't test for file existence:
Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf
This returns "myfile.txt". If we know that the file name doesn't have periods in it, we can split the string and take the first part:
(Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf).Split('.') | Select -First 1
or
(Split-Path "C:\Folder\SubFolder\myfile.txt" -Leaf).Split('.')[0]
This returns "myfile".
If the file name might include periods, to be safe, we could use the following:
$FileName = Split-Path "C:\Folder\SubFolder\myfile.txt.config.txt" -Leaf
$Extension = $FileName.Split('.') | Select -Last 1
$FileNameWoExt = $FileName.Substring(0, $FileName.Length - $Extension.Length - 1)
This returns "myfile.txt.config".
Here I prefer to use Substring() instead of Replace() because the extension preceded by a period could also be part of the name, as in my example. By using Substring we return the filename without the extension as requested.
Given any arbitrary path string, various static methods on the System.IO.Path object give the following results.
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
Following is the code that generated the above output.
[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 ) );
Writing and testing the script that generated the above uncovered some quirks about how PowerShell differs from C#, C, C++, the Windows NT command scripting language, and just about everything else with which I have any experience.
Here is one without parentheses
[io.fileinfo] 'c:\temp\myfile.txt' | % basename
This script searches in a folder and sub folders and rename files by removing their extension
Get-ChildItem -Path "C:/" -Recurse -Filter *.wctc |
Foreach-Object {
rename-item $_.fullname -newname $_.basename
}
This can be done by splitting the string a couple of times.
#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
The command below will store in a variable all the file in your folder, matchting the extension ".txt":
$allfiles=Get-ChildItem -Path C:\temp\*" -Include *.txt
foreach ($file in $allfiles) {
Write-Host $file
Write-Host $file.name
Write-Host $file.basename
}
$file gives the file with path, name and extension: c:\temp\myfile.txt
$file.name gives file name & extension: myfile.txt
$file.basename gives only filename: myfile
Here are a couple PowerShell 5.1 one-liner options that put the path at the start of the line.
'c:\temp\myfile.txt' |%{[io.fileinfo]$_ |% basename}
OR
"c:\temp\myfile.txt" | Split-Path -Leaf | %{$_ -replace '\.\w+$'}