在c#中通过Start-Job在计划任务中映射带有powershell的驱动器



我目前正在尝试在我的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

任何想法是什么原因,这是我怎么能解决它?

提前感谢您的提示

您的New-PSDrive有问题。首先检查你的PSCredential对象。然后用

更新脚本

New-PSDrive J - name -PSProvider 文件美元sharepath 证书美元信誉坚持

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

最新更新