1

I'm doing a lot of System.IO.Path operations and I was curious if it was possible to store reference to that static class in a variable so it is shorter?

Instead of writing these long winded namespace.class paths:

[System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($targetFile), [System.IO.Path]::GetFileName("newfile_$targetFile"))

It would be great to write this:

$path = [System.IO.Path]
$path.Combine($path.GetDirectoryName($targetFile), $path.GetFileName("newfile_$targetFile"))

Is there a way to do this in powershell?

2 Answers 2

5

Yes. Your suggested code is close, you just need use the :: static invocation syntax:

$path = [System.IO.Path]
$path::Combine( ... )
Sign up to request clarification or add additional context in comments.

2 Comments

nice, didnt know that!
Ahh awesome. I tried this but the ISE didn't give me any intellesense so I just assumed it was invalid. Thanks!
1

PowerShell has built-in cmdlets for some path operations:

PS C:\Windows\system32> get-command -Noun Path
CommandType Name         ModuleName                     
----------- ----         ----------                     
Cmdlet      Convert-Path Microsoft.Powershell.Management
Cmdlet      Join-Path    Microsoft.Powershell.Management
Cmdlet      Resolve-Path Microsoft.Powershell.Management
Cmdlet      Split-Path   Microsoft.Powershell.Management
Cmdlet      Test-Path    Microsoft.Powershell.Management  

Your example implemented with native PowerShell cmdlets:

Join-Path (Split-Path $targetFile) (Split-Path $targetFile -Leaf)

2 Comments

I'm still interested in if you can or can't do this, but I adjusted my example to pull filename also. Perhaps you adjust your example?
I edited my answer. Split-Path with -Leaf parameter gives you the file name

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.