Asked By june
11-Apr-07 02:26 PM

In case any newbies are reading, Marcel used a clever method for deleting the
current directory from a path. You might want to study this method and store
it away for future use.
As a bonus, it shows how to use properties and methods of strings on
non-string objects. Essentially, you apply the property/method to a string
property of the non-string object.
By the way, Marcel's solution uses the $pwd automatic variable, which always
contains the path to the current directory.
PS C:\ps-test> $pwd
Path
----
C:\ps-test
$pwd is missing from the version of about_automatic_variables shipped with
Windows PowerShell 1.0, but it will appear in updates. Sorry about that.
-------------
To delete the current directory from a file or directory path:
1. Find the length (the number of characters) of the current directory path.
Use the Length property of the file path.
PS C:\ps-test> $pwd # a PathInfo object
Path
----
C:\ps-test
PS C:\ps-test> $pwd.path # a string
C:\ps-test
PS C:\ps-test> $pwd.path.length # the length of the path string
10
(HINT: $pwd is a PathInfo object, so it doesn't have a Length property, but
its Path property is a string, which does have a Length property.)
2. Find the original, fully-qualified path of the file, which includes the
current directory. Use the FullName property of the file (or directory),
which is a string.
PS C:\ps-test> (get-childitem C:\ps-test\cad\tmp.txt).fullname
C:\ps-test\cad\tmp.txt
3. Use the SubString method on the FullName property of the original file
path. The SubString method counts over the specified number of characters,
and then selects the remainder of the string.
(HINT: You can't use the SubString method on the file path, which is a
FileInfo object, but you can use it on the value of the FullName property of
the FileInfo object, which is a string.)
For more information about the Substring method, see:
http://msdn2.microsoft.com/en-us/library/aa904307(VS.71).aspx.)
# <File> | $_.FullName
PS C:\ps-test> (dir C:\ps-test\cad\tmp.txt).FullName
C:\ps-test\cad\tmp.txt
# <File> | $_.FullName.Substring(<length-of-current-directory-path>)
PS C:\ps-test>(dir
C:\ps-test\cad\tmp.txt).FullName.SubString($pwd.path.length)
\cad.tmp.txt
In this case, Marcel used the Join-Path cmdlet to create a new path. He
appended the remainder of the file path to a new path header, C:\Foo:
$_FullName.SubString($pwd.path.length)
C:\Foo\cad\tmp.txt
This was a great solution for this task, but it's also a great strategy for
many different tasks.
--
June Blender [MSFT]
Windows PowerShell Documentation
Microsoft Corporation
This posting is provided "AS IS" with no warranties, and confers no rights.