C# code is, as a general rule, easily translated to PowerShell because C# uses the exact same underlying type system and runtime environment as PowerShell (.NET).
A few things to watch out for:
Variable assignment
C# is a type-safe language, meaning that the compiler guarantees the type of a variable and its value, as seen in your example:
HttpWebRequest request = HttpWebRequest.Create(url);
// ^ ^ \________________________/^
// | | | |
// | variable name | statement terminator ";"
// type-name |
// static method call that returns a
// value we can assign to "request"
In PowerShell:
- Types are implicit, variables are not bound to a single type (thus no need for a type name)
- Variable references are prefixed with
$
- To access static members (like the
Create()
method above), we use the following syntax:
[Namespace.TypeName]::Member
- The
;
is unnecessary, a linebreak after a statement implies termination
Thus, the above statement becomes:
$request = [System.Net.HttpWebRequest]::Create($url)
Booleans
The two C# boolean keywords (true
and false
) are, in PowerShell, represented by two automatic variables called $true
and $false
:
[System.Net.ServicePointManager]::Expect100Continue = $false
using
PowerShell doesn't have a construct comparable to C#'s using
statement. To ensure disposal of an object that implements IDisposable
, you'll have to use try
/catch
/finally
:
$req = $request.GetRequestStream()
try{
$req.Write($data, 0, $data.Length)
} catch {
throw $_
} finally {
if($req){
$req.Dispose()
}
}
Constructors
PowerShell doesn't have a new
keyword for object instantiation, but provides the New-Object
cmdlet that can wrap C# constructors:
$rdr = New-Object -TypeName System.IO.StreamReader -ArgumentList $res
Rather than:
StreamReader rdr = new StreamReader(res);
In PowerShell 5.0 and newer, you can now invoke constructors using the new
static method as well:
$rdr = [System.IO.StreamReader]::new($res)
Type casting
PowerShell supports both explicit casting that in C# would look like (typename)variable
, but again, with square brackets instead of parentheses:
[System.Net.HttpWebResponse]$request.GetResponse()
And (as of version 3.0) it supports unchecked casting as well (still with square brackets):
$request.GetResponse() -as [System.Net.HttpWebResponse]
The latter will return $null
, rather than throw an error, if the cast is not possible.
This should get you translating in no time. From the comments in your codefind, it seems you might need to translate "Wichtor's code" as well, in order to generate the $cookie
container.