1

I have to get the File directory the script is in as an variable and then split into following elements: Example Path C:\Name\Season 1\script.ps1 Now what I would need is a variable that would be var1 = "Name" and var2 = "1" which needs to just take the Number from "Season 1"

Structure will always be the same --> C:\var1\Season var2\script.ps1 just different names

Thanks in adanvce for everyone willing to help me out as I have no clue on Powershell xd

1 Answer 1

1

You can get the full path to the currently executing script using the $PsScriptRoot automatic variable. You can then use the -match operator with Regular Expressions to get the parts you want:

$PsScriptRoot -match '\\(?<Var1>.*)\\Season (?<Var2>\d+)' | Out-Null

Assuming there is a match, then the values you want will be placed in the $Matches automatic variable. So, if your script is C:\MyFavShow\Season 4\Script.ps1, then the you can get the values after running the above by simply outputting Matches:

$Matches

Which would show:

Name Value                
---- -----                
Var2 4         
Var1 MyFavShow         
0    \Directory1\Season 4

Access the items individually like this: $Matches.Var1, which would output MyFavShow.

A couple of notes:

  • $PsScriptRoot isn't populated from the command-line, only when running a script file.
  • The same matching technique can be used against any path, not just the script root. So, if you enumerate some directories (using, say, Get-ChildItem), you can still match against them.
  • $Matches does not reset after every use, only if a match is made, so if you do enumerate a lot of paths and check each one, you probably want to also check for an actual match before using the variables (as they may still be set to whatever the previous match was):
if($directory -match '\\(?<Var1>.*)\\Season (?<Var2>\d+)') {
    # Do something with the values
}
  • You can reset $Matches using: $Matches.Clear()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.