使用C#+PowerShell進行Windows系統間文件傳輸


新的winserver2016支持了一種nano模式,像以前的core模式,只能遠程管理,只支持x64,只有610M,不讓CentOS mini版獨美。

這個nano版,默認只開啟WinRM,所以只能PowerShell,安裝后F11重置密碼即可使用。

Windows Server 2008以后有Core安裝模式(安裝后磁盤占用2G+),設置密碼后,sconfig,配置遠程管理,開啟powershell與服務器管理器遠程管理。

 

下面是.net的程序方式像遠程傳輸文件。

前提是,本地與遠程的PowerShell可以連接。一般Windows默認是不開啟PowerShell的,兩邊都要運行Enable-PSRemoting(管理員),並且把目標服務器添加到信任主機中:

示例:Set-Item WSMan:\localhost\Client\TrustedHosts -Value 192.160.0.100

需要引用System.Management.Automation.dll的功能。一般它在系統多個地方出現,我從C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll

引用。

 

        static void Main(string[] args)
        {
            // 創建ps對象
            var ps = PowerShell.Create();
            ps.AddCommand("New-PSSession");// 得到一個新會話對象
            ps.AddArgument("192.168.0.100");// 目標服務器地址
            var ss = new System.Security.SecureString();
            string pwd = "123123";// 管理員密碼
            foreach (var ch in pwd)
                ss.AppendChar(ch);// 依次把char塞入安全字符串
            PSCredential cred = new PSCredential("administrator", ss);// 用安全字符串構造一個憑證
            ps.AddParameter("Credential", cred);// 憑證參數
            
            PSSession session = null;
            var ret = ps.Invoke();// 執行New-PSSession
            if (ps.Streams.Error.Count > 0)// 有錯誤
            {
                Console.WriteLine(ps.Streams.Error[0]);
                return;
            }
            else
                session = ret[0].BaseObject as PSSession;
                
            ps.Commands.Clear();// 清理命令,重用PS對象
            ps.AddCommand("cp");// Copy-Item
            ps.AddArgument("C:\\Users\\Fyter\\文檔\\測試用文件.txt");// 本地文件
            ps.AddParameter("Destination", "c:\\");// 會話所連接的目標計算機硬盤位置
            ps.AddParameter("ToSession", session);// 目標會話
            var result = ps.Invoke();// 執行
            if(ps.Streams.Error.Count > 0)
                Console.WriteLine(ps.Streams.Error[0]);
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM