转换另一种语言的PowerShell或使用PowerShell中的语言 [英] Converting another language to powershell or using the language in powershell

查看:786
本文介绍了转换另一种语言的PowerShell或使用PowerShell中的语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个代码



  //网址是完整的目标路径(包括文件名,例如HTTPS:/ /mysite.sharepoint.com/Documents/Test.txt)

//从Wichtor代码
//数据生成的曲奇是的CookieContainer是包含文件内容的字节数组(使用一个FileStream加载)

System.Net.ServicePointManager.Expect100Continue = FALSE;
HttpWebRequest的要求= HttpWebRequest.Create(URL)为HttpWebRequest的;
request.Method =PUT;
request.Accept =* / *;
request.ContentType =的multipart / form-data的;字符集= UTF-8;
request.CookieContainer =饼干; request.AllowAutoRedirect = FALSE;
request.UserAgent =Mozilla的/ 5.0(兼容; MSIE 9.0; Windows NT的6.1; WOW64;三叉戟/ 5.0);
request.Headers.Add(接受语言,EN-US);
request.Headers.Add(翻译,F); request.Headers.Add(缓存控制,无缓存); request.ContentLength = data.Length;使用(流REQ = request.GetRequestStream())
{req.Write(数据,0,data.Length)

; }

HttpWebResponse响应=(HttpWebResponse)request.GetResponse();
溪水库= response.GetResponseStream();
StreamReader的RDR =新的StreamReader(RES);
串rawResponse = rdr.ReadToEnd();
response.Close();
rdr.Close();



这显然成功上传大文件到的SharePoint 网站,但是我代码是在的PowerShell 。反正是有其现在的形式在PowerShell中使用此,甚至将其转换为PowerShell的?


解决方案

C#代码,作为一般规则,很容易转换为PowerShell的,因为C#使用完全相同的基本类型的系统和运行环境。作为PowerShell的(.NET)



有几件事情需要注意的:



变量赋值



C#是一种类型安全的语言,这意味着编译器保证了变量和它的价值的键入的,因为在你的榜样看出:



<预类=郎-CS prettyprint-覆盖> HttpWebRequest的要求= HttpWebRequest.Create(URL);
// ^^ \ ________________________ / ^
// | | | |
// |变量名称|声明终结者;
//类型名称|
//返回,我们可以分配给请求


$ B A
//值静态方法调用$ b

在PowerShell中:



<醇>
  • 类型是隐含的,变量不绑定到单个类型(因此,没有必要为一种类型的名称)

  • 变量引用的前缀为 $

  • 要访问静态成员(如创建()以上法),我们使用的语法如下:


    • [ Namespace.TypeName] ::会员


  • ; 是不必要的,一个语句之后断行意味着终止



  • 因此,上面的语句变成了:



    <预类=郎PSH prettyprint-覆盖> $请求= [System.Net.HttpWebRequest] ::创建($网址)






    布尔



    这两个C#布尔关键字(真正)的,在PowerShell中,由两个被称为自动变量来表示 $真正 $假



    <预类=郎PSH prettyprint-覆盖> [System.Net.ServicePointManager] :: Expect100Continue = $虚假






    使用



    PowerShell不具有构造可比的 C#的使用语句。为了确保处理对象的实现的IDisposable ,你将不得不使用尝试 / / 最后



    <预类=郎PSH prettyprint-覆盖> $ REQ = $ request.GetRequestStream()
    尝试{
    $ req.Write($的数据,0,$ data.Length)
    } {赶上
    扔$ _
    } {最后
    如果($ REQ){
    $ req.Dispose()
    }
    }






    构造



    PowerShell不有对象实例化一个关键字,但提供了新对象的cmdlet,可以换C#构造函数:



    <预类=郎PSH prettyprint-覆盖> $ RDR =新对象-TypeName就是System.IO.StreamReader -ArgumentList $水库

    而不是:



    <预类=郎-CS prettyprint,覆盖> StreamReader的RDR =新的StreamReader(RES);






    的类型转换



    的PowerShell支持的明确铸造的,在C#看起来像(类型名)变量,但同样,用方括号代替括号:



    <预类=郎PSH prettyprint-覆盖> [System.Net.HttpWebResponse] $ request.GetResponse()

    和(如3.0版),它支持的选中铸造的以及(仍与方括号中):



    <预类=郎PSH prettyprint-覆盖> $ request.GetResponse() - 作为[System.Net.HttpWebResponse]

    后者将返回 $空,而不是抛出一个错误,如果转换是不可能的。






    这应该让你在任何时间转换。从您codefind的意见,看来你可能需要翻译Wichtor代码为好,以生成 $饼干容器中。


    I have found this code

    // "url" is the full destination path (including filename, i.e. https://mysite.sharepoint.com/Documents/Test.txt) 
    
    // "cookie" is the CookieContainer generated from Wichtor's code 
    // "data" is the byte array containing the files contents (used a FileStream to load) 
    
    System.Net.ServicePointManager.Expect100Continue = false; 
    HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; 
    request.Method = "PUT"; 
    request.Accept = "*/*"; 
    request.ContentType = "multipart/form-data; charset=utf-8"; 
    request.CookieContainer = cookie; request.AllowAutoRedirect = false; 
    request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; 
    request.Headers.Add("Accept-Language", "en-us"); 
    request.Headers.Add("Translate", "F"); request.Headers.Add("Cache-Control", "no-cache"); request.ContentLength = data.Length; 
    
    using (Stream req = request.GetRequestStream()) 
    { req.Write(data, 0, data.Length); } 
    
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Stream res = response.GetResponseStream(); 
    StreamReader rdr = new StreamReader(res); 
    string rawResponse = rdr.ReadToEnd(); 
    response.Close();
    rdr.Close();
    

    Which apparently successfully uploads a large file to a sharepoint site, however my code is in powershell. Is there anyway to use this in powershell in its form now or even convert this to powershell?

    解决方案

    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:

    1. Types are implicit, variables are not bound to a single type (thus no need for a type name)
    2. Variable references are prefixed with $
    3. To access static members (like the Create() method above), we use the following syntax:
      • [Namespace.TypeName]::Member
    4. 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); 
    


    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.

    这篇关于转换另一种语言的PowerShell或使用PowerShell中的语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆