Thraka
Thraka

Reputation: 2164

is it possible to use a variable to reference a .NET static class in powershell?

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?

Upvotes: 1

Views: 61

Answers (2)

Martin Brandl
Martin Brandl

Reputation: 58971

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)

Upvotes: 1

latkin
latkin

Reputation: 16792

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

$path = [System.IO.Path]
$path::Combine( ... )

Upvotes: 5

Related Questions