簡體   English   中英

如何從 Windows 服務 map 網絡驅動器

[英]How can I map a network drive from a Windows Service

我有一個 windows 服務 (C#) 作為本地系統運行。 我希望能夠讀取我的數據庫並運行 PowerShell 命令和腳本。 我能夠運行大多數腳本,但我的測試機掛在這個上:

NET USE Z: /Delete /y
NET USE Z: \\TEST2\ProgramData

我可以在計算機上運行這些命令並且一切正常,但是當我嘗試從我的 Windows 服務中運行這些命令時,它會在運行腳本的線路上運行。

    private static bool RunPSCommand(string command, out string output)
    {
        // create Powershell runspace
        Runspace runspace = RunspaceFactory.CreateRunspace();

        // open it
        runspace.Open();

        // create a pipeline and feed it the script text
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(command);

        // add an extra command to transform the script output objects into nicely formatted strings
        // remove this line to get the actual objects that the script returns. For example, the script
        // "Get-Process" returns a collection of System.Diagnostics.Process instances.
        pipeline.Commands.Add("Out-String");

        // execute the script
        try
        {
            StringBuilder stringBuilder = new StringBuilder();

            Collection<PSObject> results = pipeline.Invoke();
            if (pipeline.HadErrors)
            {
                var errors = pipeline.Error.ReadToEnd();
                foreach (object error in errors)
                {
                    stringBuilder.AppendLine(error.ToString());
                }
            }

            // close the runspace
            runspace.Close();

            // convert the script result into a single string        
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            output = stringBuilder.ToString();
            return true;
        }
        catch (CommandNotFoundException e)
        {
            output = e.Message;
            return false;
        }

        catch (Exception e)
        {
            output = e.Message;
            return false;
        }
    }

我不確定為什么這如此困難。 三天以來,我一直在努力解決這個問題,並嘗試了從網絡使用到 DOM 對象的所有選項

NET USE Z: /Delete /y
(New-Object -Com WScript.Network).MapNetworkDrive("z:" , "\\test2\programdata")

我試圖從服務中執行此操作,但切換到在用戶 session 上運行的應用程序。 它以這種方式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM