0

我目前正在尝试在我的 Web 服务上运行一个 powershell 脚本,它将驱动器映射到另一个系统上的共享文件夹并将一个文件夹复制到它。我目前遇到的奇怪问题是脚本似乎执行得很好,但是运行脚本的作业似乎没有正确完成。因此,我必须为强制完成任务设置超时,否则它根本不会完成。然而,这并不是我真正想要的,因为如果脚本花费的时间比预期的长等,它可能会产生一些令人讨厌的副作用。另一方面,我希望在给定的场景中尽可能快地执行,所以我想要让脚本“自然”完成。

这是我目前的设置

C# Web 服务调用 powershell 脚本,如下所示:

public Collection<PSObject> executeCommand(String pCommand, String pName)
        {
            // Call the script
            var runspaceConfiguration = RunspaceConfiguration.Create();
            var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();
            var pipeline = runspace.CreatePipeline();

            pipeline.Commands.AddScript(pCommand);
            pipeline.Commands.AddScript("Wait-Job -Name " + pName + " -Timeout 60");
            pipeline.Commands.AddScript("Receive-Job -Name " + pName);

            return pipeline.Invoke();
        }


String shareArguments = "some stuff here";
        String shareCommandName = "copyFolder";
        String shareCommand = "Start-Job -filepath " + currentDirectory + "\\scripts\\copyFolder.ps1 -ArgumentList " + shareArguments + " -Name " + shareCommandName + " -RunAs32";
        Collection<PSObject> results1 = executeCommand(shareCommand, shareCommandName);

        StreamWriter sharestream = new StreamWriter("D:\\shareoutput.txt");
        foreach (PSObject obj in results1)
        {
            sharestream.WriteLine(obj.ToString());
        }
        sharestream.Close();

脚本本身:

   param($sharepath,$shareuser,$sharepassword,$hostname,$sourcefolder)

   # create a credentials object
   $secpasswd = ConvertTo-SecureString $sharepassword -AsPlainText -Force
   Write-Output "0"
   $cred = New-Object System.Management.Automation.PSCredential ($shareuser, $secpasswd)
   Write-Output "1"
   # Access the share
   New-PSDrive -Name J -PSProvider FileSystem -Root $sharepath -Credential $cred
   Write-Output "2"
   # Copy the folder including the file
   Copy-Item $sourcefolder "J:\" -Recurse -Force
   Write-Output "3"
   # Unmap drive
   Remove-PSDrive -Name J

当我检索作业的调试输出时,输出如下所示。所以似乎 New-PSDrive 调用似乎以某种方式在这里阻塞:

0
1

知道这是什么原因以及如何解决它吗?

提前感谢您的任何提示

4

1 回答 1

0

您对 New-PSDrive 有疑问。首先检查您的 PSCredential 对象。然后更新脚本

New-PSDrive -Name J -PSProvider FileSystem -Root $sharepath -Credential $cred -Persist

完美文章: https ://technet.microsoft.com/en-us/library/hh849829.aspx

于 2016-11-02T19:49:39.153 回答