File size: 26,489 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// This cmdlet start invocation of jobs in background.
    /// </summary>
    [Cmdlet(VerbsLifecycle.Start, "Job", DefaultParameterSetName = StartJobCommand.ComputerNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096796")]
    [OutputType(typeof(PSRemotingJob))]
    public class StartJobCommand : PSExecutionCmdlet, IDisposable
    {
        #region Private members

        private static readonly string s_startJobType = "BackgroundJob";

        #endregion

        #region Parameters

        private const string DefinitionNameParameterSet = "DefinitionName";

        /// <summary>
        /// JobDefinition Name.
        /// </summary>
        [Parameter(Position = 0, Mandatory = true,
                   ParameterSetName = StartJobCommand.DefinitionNameParameterSet)]
        [ValidateTrustedData]
        [ValidateNotNullOrEmpty]
        public string DefinitionName
        {
            get { return _definitionName; }

            set { _definitionName = value; }
        }

        private string _definitionName;

        /// <summary>
        /// JobDefinition file path.
        /// </summary>
        [Parameter(Position = 1,
                   ParameterSetName = StartJobCommand.DefinitionNameParameterSet)]
        [ValidateNotNullOrEmpty]
        public string DefinitionPath
        {
            get { return _definitionPath; }

            set { _definitionPath = value; }
        }

        private string _definitionPath;

        /// <summary>
        /// Job SourceAdapter type for this job definition.
        /// </summary>
        [Parameter(Position = 2,
            ParameterSetName = StartJobCommand.DefinitionNameParameterSet)]
        [ValidateNotNullOrEmpty]
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
        public string Type
        {
            get { return _definitionType; }

            set { _definitionType = value; }
        }

        private string _definitionType;

        /// <summary>
        /// Friendly name for this job object.
        /// </summary>
        [Parameter(ValueFromPipelineByPropertyName = true,
                   ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ValueFromPipelineByPropertyName = true,
                   ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ValueFromPipelineByPropertyName = true,
                   ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        public virtual string Name
        {
            get
            {
                return _name;
            }

            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _name = value;
                }
            }
        }

        private string _name;

        /// <summary>
        /// Command to execute specified as a string. This can be a single
        /// cmdlet, an expression or anything that can be internally
        /// converted into a ScriptBlock.
        /// </summary>
        /// <remarks>This is used in the in process case with a
        /// "ValueFromPipelineProperty" enabled in order to maintain
        /// compatibility with v1.0</remarks>
        [Parameter(Position = 0,
                   Mandatory = true,
                   ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [ValidateTrustedData]
        [Alias("Command")]
        public override ScriptBlock ScriptBlock
        {
            get
            {
                return base.ScriptBlock;
            }

            set
            {
                base.ScriptBlock = value;
            }
        }

        #region Suppress PSRemotingBaseCmdlet parameters

        // suppress all the parameters from PSRemotingBaseCmdlet
        // which should not be part of Start-PSJob

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override PSSession[] Session
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override string[] ComputerName
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Not used for OutOfProc jobs.  Suppressing this parameter.
        /// </summary>
        public override SwitchParameter EnableNetworkAccess
        {
            get { return false; }
        }

        /// <summary>
        /// Suppress SSHTransport.
        /// </summary>
        public override SwitchParameter SSHTransport
        {
            get { return false; }
        }

        /// <summary>
        /// Suppress SSHConnection.
        /// </summary>
        public override Hashtable[] SSHConnection
        {
            get { return null; }
        }

        /// <summary>
        /// Suppress UserName.
        /// </summary>
        public override string UserName
        {
            get { return null; }
        }

        /// <summary>
        /// Suppress KeyFilePath.
        /// </summary>
        public override string KeyFilePath
        {
            get { return null; }
        }

        /// <summary>
        /// Suppress HostName.
        /// </summary>
        public override string[] HostName
        {
            get { return null; }
        }

        /// <summary>
        /// Suppress Subsystem.
        /// </summary>
        public override string Subsystem
        {
            get { return null; }
        }

        #endregion

        /// <summary>
        /// Credential to use for this job.
        /// </summary>
        [Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        [Credential]
        public override PSCredential Credential
        {
            get
            {
                return base.Credential;
            }

            set
            {
                base.Credential = value;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override int Port
        {
            get
            {
                return 0;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override SwitchParameter UseSSL
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override string ConfigurationName
        {
            get
            {
                return base.ConfigurationName;
            }

            set
            {
                base.ConfigurationName = value;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override Int32 ThrottleLimit
        {
            get
            {
                return 0;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override string ApplicationName
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override Uri[] ConnectionUri
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Filepath to execute as a script.
        /// </summary>
        [Parameter(
            Position = 0,
            Mandatory = true,
            ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [ValidateTrustedData]
        public override string FilePath
        {
            get
            {
                return base.FilePath;
            }

            set
            {
                base.FilePath = value;
            }
        }

        /// <summary>
        /// Literal Filepath to execute as a script.
        /// </summary>
        [Parameter(
            Mandatory = true,
            ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        [ValidateTrustedData]
        [Alias("PSPath", "LP")]
        public string LiteralPath
        {
            get
            {
                return base.FilePath;
            }

            set
            {
                base.FilePath = value;
                base.IsLiteralPath = true;
            }
        }

        /// <summary>
        /// Use basic authentication to authenticate the user.
        /// </summary>
        [Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        public override AuthenticationMechanism Authentication
        {
            get
            {
                return base.Authentication;
            }

            set
            {
                base.Authentication = value;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override string CertificateThumbprint
        {
            get
            {
                return base.CertificateThumbprint;
            }

            set
            {
                base.CertificateThumbprint = value;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override SwitchParameter AllowRedirection
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override Guid[] VMId
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override string[] VMName
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override string[] ContainerId
        {
            get
            {
                return null;
            }
        }

        /// <summary>
        /// Overriding to suppress this parameter.
        /// </summary>
        public override SwitchParameter RunAsAdministrator
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Extended Session Options for controlling the session creation. Use
        /// "New-WSManSessionOption" cmdlet to supply value for this parameter.
        /// </summary>
        /// <remarks>
        /// This is not declared as a Parameter for Start-PSJob as this is not
        /// used for background jobs.
        /// </remarks>
        public override PSSessionOption SessionOption
        {
            get
            {
                return base.SessionOption;
            }

            set
            {
                base.SessionOption = value;
            }
        }

        /// <summary>
        /// Script that is used to initialize the background job.
        /// </summary>
        [Parameter(Position = 1,
                   ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(Position = 1,
                   ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(Position = 1,
                   ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        [ValidateTrustedData]
        public virtual ScriptBlock InitializationScript
        {
            get { return _initScript; }

            set { _initScript = value; }
        }

        private ScriptBlock _initScript;

        /// <summary>
        /// Gets or sets an initial working directory for the powershell background job.
        /// </summary>
        [Parameter]
        [ValidateNotNullOrWhiteSpace]
        public string WorkingDirectory { get; set; }

        /// <summary>
        /// Launches the background job as a 32-bit process. This can be used on
        /// 64-bit systems to launch a 32-bit wow process for the background job.
        /// </summary>
        [Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        public virtual SwitchParameter RunAs32 { get; set; }

        /// <summary>
        /// Powershell Version to execute the background job.
        /// </summary>
        [Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        [ValidateNotNullOrEmpty]
        public virtual Version PSVersion
        {
            get
            {
                return _psVersion;
            }

            set
            {
                // PSVersion value can only be 5.1 for Start-Job.
                if (!(value.Major == 5 && value.Minor == 1))
                {
                    throw new ArgumentException(
                        StringUtil.Format(RemotingErrorIdStrings.PSVersionParameterOutOfRange, value, "PSVersion"));
                }

                _psVersion = value;
            }
        }

        private Version _psVersion;

        /// <summary>
        /// InputObject.
        /// </summary>
        [Parameter(ValueFromPipeline = true,
                   ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ValueFromPipeline = true,
                   ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ValueFromPipeline = true,
                   ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        [ValidateTrustedData]
        public override PSObject InputObject
        {
            get { return base.InputObject; }

            set { base.InputObject = value; }
        }

        /// <summary>
        /// ArgumentList.
        /// </summary>
        [Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)]
        [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)]
        [ValidateTrustedData]
        [Alias("Args")]
        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public override object[] ArgumentList
        {
            get { return base.ArgumentList; }

            set { base.ArgumentList = value; }
        }

        #endregion Parameters

        #region Overrides

        /// <summary>
        /// 1. Set the throttling limit and reset operations complete
        /// 2. Create helper objects
        /// 3. For async case, write the async result object down the
        ///    pipeline.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (!File.Exists(PowerShellProcessInstance.PwshExePath))
            {
                // The pwsh executable file is not found under $PSHOME.
                // This means that PowerShell is currently being hosted in another application,
                // and 'Start-Job' is not supported by design in that scenario.
                string message = StringUtil.Format(
                    RemotingErrorIdStrings.IPCPwshExecutableNotFound,
                    PowerShellProcessInstance.PwshExePath);

                var errorRecord = new ErrorRecord(
                    new PSNotSupportedException(message),
                    "IPCPwshExecutableNotFound",
                    ErrorCategory.NotInstalled,
                    PowerShellProcessInstance.PwshExePath);

                ThrowTerminatingError(errorRecord);
            }

            if (RunAs32.IsPresent && Environment.Is64BitProcess)
            {
                // We cannot start a 32-bit 'pwsh' process from a 64-bit 'pwsh' installation.
                string message = RemotingErrorIdStrings.RunAs32NotSupported;
                var errorRecord = new ErrorRecord(
                    new PSNotSupportedException(message),
                    "RunAs32NotSupported",
                    ErrorCategory.InvalidOperation,
                    targetObject: null);

                ThrowTerminatingError(errorRecord);
            }

            if (WorkingDirectory != null && !InvokeProvider.Item.IsContainer(WorkingDirectory))
            {
                string message = StringUtil.Format(RemotingErrorIdStrings.StartJobWorkingDirectoryNotFound, WorkingDirectory);
                var errorRecord = new ErrorRecord(
                    new DirectoryNotFoundException(message),
                    "DirectoryNotFoundException",
                    ErrorCategory.InvalidOperation,
                    targetObject: null);

                ThrowTerminatingError(errorRecord);
            }

            if (WorkingDirectory == null)
            {
                try
                {
                    WorkingDirectory = SessionState.Internal.CurrentLocation.Path;
                }
                catch (PSInvalidOperationException)
                {
                }
            }

            CommandDiscovery.AutoloadModulesWithJobSourceAdapters(this.Context, this.CommandOrigin);

            if (ParameterSetName == DefinitionNameParameterSet)
            {
                return;
            }

            // since jobs no more depend on WinRM
            // we will have to skip the check for the same
            SkipWinRMCheck = true;

            base.BeginProcessing();
        }

        /// <summary>
        /// Create a throttle operation using NewProcessConnectionInfo
        /// ie., Out-Of-Process runspace.
        /// </summary>
        protected override void CreateHelpersForSpecifiedComputerNames()
        {
            // If we're in ConstrainedLanguage mode and the system is in lockdown mode,
            // ensure that they haven't specified a ScriptBlock or InitScript - as
            // we can't protect that boundary.
            if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
                (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) &&
                ((ScriptBlock != null) || (InitializationScript != null)))
            {
                ThrowTerminatingError(
                    new ErrorRecord(
                        new PSNotSupportedException(RemotingErrorIdStrings.CannotStartJobInconsistentLanguageMode),
                            "CannotStartJobInconsistentLanguageMode",
                            ErrorCategory.PermissionDenied,
                            Context.LanguageMode));
            }

            NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(this.Credential);
            connectionInfo.InitializationScript = _initScript;
            connectionInfo.AuthenticationMechanism = this.Authentication;
            connectionInfo.PSVersion = this.PSVersion;
            connectionInfo.WorkingDirectory = this.WorkingDirectory;

            RemoteRunspace remoteRunspace = (RemoteRunspace)RunspaceFactory.CreateRunspace(connectionInfo, this.Host,
                        Utils.GetTypeTableFromExecutionContextTLS());

            remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived;

            Pipeline pipeline = CreatePipeline(remoteRunspace);

            IThrottleOperation operation =
                new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline);

            Operations.Add(operation);
        }
        /// <summary>
        /// The expression will be executed in the remote computer if a
        /// remote runspace parameter or computer name is specified. If
        /// none other than command parameter is specified, then it
        /// just executes the command locally without creating a new
        /// remote runspace object.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (ParameterSetName == DefinitionNameParameterSet)
            {
                // Get the Job2 object from the Job Manager for this definition name and start the job.
                string resolvedPath = null;
                if (!string.IsNullOrEmpty(_definitionPath))
                {
                    ProviderInfo provider = null;
                    System.Collections.ObjectModel.Collection<string> paths =
                        this.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(_definitionPath, out provider);

                    // Only file system paths are allowed.
                    if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotFSProvider,
                            _definitionName,
                            _definitionPath,
                            provider.FullName);
                        WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotFileSystemProvider",
                            ErrorCategory.InvalidArgument, null));

                        return;
                    }

                    // Only a single file path is allowed.
                    if (paths.Count != 1)
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotSingle,
                            _definitionName,
                            _definitionPath);
                        WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotSingle",
                            ErrorCategory.InvalidArgument, null));

                        return;
                    }

                    resolvedPath = paths[0];
                }

                List<Job2> jobs = JobManager.GetJobToStart(_definitionName, resolvedPath, _definitionType, this, false);

                if (jobs.Count == 0)
                {
                    string message = (_definitionType != null) ?
                        StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound2, _definitionType, _definitionName) :
                        StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound1, _definitionName);

                    WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameNotFound",
                        ErrorCategory.ObjectNotFound, null));

                    return;
                }

                if (jobs.Count > 1)
                {
                    string message = StringUtil.Format(RemotingErrorIdStrings.StartJobManyDefNameMatches, _definitionName);
                    WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameMoreThanOneMatch",
                        ErrorCategory.InvalidResult, null));

                    return;
                }

                // Start job.
                Job2 job = jobs[0];
                job.StartJob();

                // Write job object to host.
                WriteObject(job);

                return;
            }

            if (_firstProcessRecord)
            {
                _firstProcessRecord = false;

                PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations,
                        ScriptBlock.ToString(), ThrottleLimit, _name);

                job.PSJobTypeName = s_startJobType;

                this.JobRepository.Add(job);
                WriteObject(job);
            }

            // inject input
            if (InputObject != AutomationNull.Value)
            {
                foreach (IThrottleOperation operation in Operations)
                {
                    ExecutionCmdletHelper helper = (ExecutionCmdletHelper)operation;
                    helper.Pipeline.Input.Write(InputObject);
                }
            }
        }

        private bool _firstProcessRecord = true;

        /// <summary>
        /// InvokeAsync would have been called in ProcessRecord. Wait here
        /// for all the results to become available.
        /// </summary>
        protected override void EndProcessing()
        {
            // close the input stream on all the pipelines
            CloseAllInputStreams();
        }

        #endregion Overrides

        #region IDisposable Overrides

        /// <summary>
        /// Dispose the cmdlet.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Internal dispose method which does the actual disposing.
        /// </summary>
        /// <param name="disposing">Whether called from dispose or finalize.</param>
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                CloseAllInputStreams();
            }
        }

        #endregion IDisposable Overrides
    }
}