I run the command (Get-Location), and it returns the current location of a file.
Example: c:\folder1\folder2\folder3\XXX\folder4\folder5
Firstly, from the above, I want to get the value of XXX and let it equal to a variable. How can I do this?
Secondly, I want to get the value of c:\folder1\folder2\folder3\XXX\folder4\
an开发者_如何学God let it equal to a variable. How can I do this?
I have used the placeholders folder1
, folder2
, etc. for illustration. These are dynamic.
To answer your second question first: to get the parent to the full path, use Split-Path:
$var = Split-Path -parent "c:\folder1\folder2\folder3\XXX\folder4\folder5"
For your other question, this function will split all the elements of your path and return them into an array:
function Split-Paths($pth)
{
while($pth)
{
Split-Path -leaf $pth
$pth = Split-Path -parent $pth
}
}
You can then grab the 5th element like this:
$xxx = (Split-Paths "c:\folder1\folder2\folder3\XXX\folder4\folder5")[-5]
Note that the function returns the elements in "reverse" order, so you use a negative index to index from the end of the array.
Some of these answers are pretty close, but everyone is forgetting their shell-fu.
$FirstAnswer = (Get-Item ..\..).Name
$SecondAnswer = (Get-Item ..).FullName
To get the path into a variable, you can do something like this:
$a = (Get-Location).Path
Then, if you want to set the value of the 'XXX' part of your path to a variable, you can use the split() function:
$x = $a.split('\')[4]
You could do this with a regular expression:
PS> $path = 'c:\folder1\folder2\folder3\XXX\folder4\folder5'
PS> $path -match 'c:\\([^\\]+)\\([^\\]+)\\([^\\]+)\\([^\\]+)'
True
PS> $matches
Name Value
---- -----
4 XXX
3 folder3
2 folder2
1 folder1
0 c:\folder1\folder2\folder3\XXX
You can use regular expressions:
$rawtext = "If it interests you, my e-mail address is tobias@powershell.com."
# Simple pattern recognition:
$rawtext -match "your regular expression"
*True*
# Reading data matching the pattern from raw text:
$matches
$matches
returns the result.
For more information, check Chapter 13. Text and Regular Expressions (requires registration).
精彩评论