7

I'm trying to get Uri to stop encoding '/' As explained here: GETting a URL with an url-encoded slash

But how to achieve the same in powershell ?

I'm trying to follow the route of accessing private property and changing it's value but I can't get it to work.

[Uri].GetProperties([System.Reflection.BindingFlags]::NonPublic) - returns nothing

Any ideas?

Community
  • 1
  • 1
Jammes
  • 291
  • 1
  • 4
  • 8

4 Answers4

7

This is working solution for PowerShell:

$uri = [Uri]"http://example.com/%2F"
# access the .PathAndQuery field to initialize the Uri object
$pathAndQuery = $uri.PathAndQuery
$flagsField = $uri.GetType().GetField("m_Flags", [Reflection.BindingFlags]::NonPublic -bor [Reflection.BindingFlags]::Instance)
$flagsValue = [UInt64]$flagsField.GetValue($uri)
# remove flags Flags.PathNotCanonical and Flags.QueryNotCanonical
$flagsValue = [UInt64]($flagsValue -band (-bnot 0x30));
$flagsField.SetValue($uri, $flagsValue)
Write-Host $uri.AbsoluteUri

Thanks to google-api-dotnet-client path :-) please note, that there is some difference with .net 2.0, my code is working for > .net 2.0 (for <= 2.0 versions, the type of flagsValue object will be [Int32] instead of [Uint64])

Boo
  • 1,634
  • 3
  • 20
  • 29
1

try this (like in your link):

$uri.GetType().GetField("m_Flags", [System.Reflection.BindingFlags]::Instance -bor `
 [System.Reflection.BindingFlags]::NonPublic)

to get non public properties:

$uri.GetType().GetProperties( [System.Reflection.BindingFlags]::Instance -bor `
[System.Reflection.BindingFlags]::NonPublic )
CB.
  • 58,865
  • 9
  • 159
  • 159
1

Taking that other post as what you need, you want this:

$uri = [uri]"http://example.com/%2F"
$f = [uri].getfield("m_Flags", "nonpublic,instance")
$v = [int]($f.getvalue($uri))
$f.setvalue($uri, [uint64]($v -band (-bnot 0x30)))

PowerShell's -bnot and -band bitwise operators don't work with any types bigger than [int] so I'm downcasting to [int] which does not overflow for the above case (which means flag values beyond [int]::maxvalue are not present.)

x0n
  • 51,312
  • 7
  • 89
  • 111
  • The code works fine but it has no effect on Uri unfortunately. I'm getting http://0.0.0.0/myoriginalip/restofthepath (still parsed by Uri so '%2F' is still reversed to original '/' I ran the same code in .net unit test and it works fine. I don't really understand why Powershell doesn't follow the same pattern. If anyone has better luck do let me know. – Jammes Oct 04 '12 at 09:14
  • It is important to access PathAndQuery before doing the internal manipulation of the state. You are skipping that part of the code. – Rasmus Faber Aug 29 '13 at 13:49
0
$uri.GetType().GetProperties('Instance,NonPublic')
Shay Levy
  • 121,444
  • 32
  • 184
  • 206