示例#1
0
        public void ExecuteWorkDirTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new PowerShellRuntime())
                {
                    var outPath = "workDirTest.txt";
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute($"'test' | Out-File workDirTest.txt");
                    FileAssert.Exists(outPath);

                    outPath = Path.Combine(tempDir.TempPath, outPath);
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute($"'test' | Out-File workDirTest.txt", tempDir.TempPath);
                    FileAssert.Exists(outPath);
                }
        }
示例#2
0
        public void ExecuteFileTest()
        {
            using (var tempDir = TempDirectory.Create())
                using (var runtime = new PowerShellRuntime("ExecuteFileTest"))
                {
                    var filePath = Path.Combine(tempDir.TempPath, "ExecuteFileTest.ps1");
                    File.WriteAllText(filePath, @"
param($FileArgs)
return $FileArgs.Arg1 + $FileArgs.Arg2
");
                    var res = runtime.ExecuteFile(filePath, null, new Dictionary <string, object>
                    {
                        { "Arg1", 2 },
                        { "Arg2", 3 }
                    });
                    Assert.AreEqual(5, res);
                }
        }
示例#3
0
        public void GetFunctionTest()
        {
            using (var tempDir = TempDirectory.Create())
            {
                using (var ps = new PowerShellRuntime("GetFunctionTest"))
                {
                    Assert.IsTrue(ps.GetFunction("TestFunc") == null);
                    var path = Path.Combine(tempDir.TempPath, "GetFunctionTest.psm1");
                    File.WriteAllText(path, @"
function TestFunc()
{
    return 4 + 4
}
");
                    ps.ImportModule(path);
                    Assert.IsTrue(ps.GetFunction("TestFunc") != null);
                }
            }
        }
示例#4
0
        /// <summary>
        /// Constructs a new instance of <see cref="AzPredictor"/> to use in PowerShell's prediction subsystem.
        /// </summary>
        public AzPredictor()
        {
            _powerShellRuntime = new PowerShellRuntime();
            _surveyHelper      = new AzPredictorSurveyHelper(_powerShellRuntime);

            // To make import-module fast, we'll do all the initialization in a task.
            // Slow initialization may make opening a PowerShell window slow if "Import-Module" is added to the user's profile.
            Task.Run(() =>
            {
                _settings  = Settings.GetSettings();
                _azContext = new AzContext(_powerShellRuntime)
                {
                    IsInternal = (_settings.SetAsInternal == true) ? true : false,
                };

                _azContext.UpdateContext();
                // This will run the script in the right context.
                var _            = _azContext.PowerShellVersion;
                _telemetryClient = new AzPredictorTelemetryClient(_azContext);
                _service         = new AzPredictorService(_settings.ServiceUri, _telemetryClient, _azContext);
                _isInitialized   = true;
            });
        }
示例#5
0
        /// <inhericdoc/>
        public void Dispose()
        {
            if (_predictionRequestCancellationSource != null)
            {
                _predictionRequestCancellationSource.Dispose();
                _predictionRequestCancellationSource = null;
            }

            if (_surveyHelper is IDisposable disposableSurveyHelper)
            {
                disposableSurveyHelper.Dispose();
                _surveyHelper = null;
            }

            if (_powerShellRuntime != null)
            {
                _powerShellRuntime.Dispose();
                _powerShellRuntime = null;
            }

            _externalDisposableObjects.ForEach((o) => o?.Dispose());
            _externalDisposableObjects.Clear();
        }
示例#6
0
        public void ExecuteWorkDirTest()
        {
            using (var tempDir = TempDirectory.Create())
            {
                Directory.SetCurrentDirectory(tempDir.TempPath);
                using (var runtime = new PowerShellRuntime("ExecuteWorkDirTest"))
                {
                    var outPath = "workDirTest.txt";
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute($"'test' | Out-File workDirTest.txt");
                    FileAssert.Exists(outPath);

                    FileSystem.CreateDirectory("subdirectory");
                    var tempDir2 = Path.Combine(tempDir.TempPath, "subdirectory");
                    outPath = Path.Combine(tempDir2, outPath);
                    FileSystem.DeleteFile(outPath);
                    FileAssert.DoesNotExist(outPath);
                    runtime.Execute($"'test' | Out-File workDirTest.txt", tempDir2);
                    FileAssert.Exists(outPath);
                }
                Directory.SetCurrentDirectory("\\");
            }
        }
示例#7
0
 public AzContext(PowerShellRuntime powerShellRuntime) => _powerShellRuntime
        private void RunScript(string runtimeName, Action <PowerShellRuntime> startAction, Dictionary <string, object> variables, bool asyncExec = true)
        {
            variables.Add("Game", Game.GetClone());
            variables.Add("PlayniteApi", playniteApi);
            variables.Add("IsPlayAction", asyncExec);
            playRuntime = new PowerShellRuntime(runtimeName);

            if (asyncExec)
            {
                watcherToken = new CancellationTokenSource();
                variables.Add("CancelToken", watcherToken.Token);
                stopWatch = Stopwatch.StartNew();
                playTask  = Task.Run(() =>
                {
                    try
                    {
                        startAction(playRuntime);

                        if (!isDisposed) // Should not be called when we reached this from cancel state.
                        {
                            execContext.Post((_) => InvokeOnStopped(new GameStoppedEventArgs()
                            {
                                SessionLength = Convert.ToUInt64(stopWatch.Elapsed.TotalSeconds)
                            }), null);
                        }
                    }
                    catch (Exception exc) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(exc, "Play script failed.");
                        execContext.Post((_) =>
                        {
                            InvokeOnStopped(new GameStoppedEventArgs()
                            {
                                SessionLength = Convert.ToUInt64(stopWatch.Elapsed.TotalSeconds)
                            });
                            Dialogs.ShowMessage(
                                exc.Message,
                                LOC.ErrorPlayScriptAction,
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                        }, null);
                    }
                    finally
                    {
                        if (!playRuntime.IsDisposed)
                        {
                            playRuntime?.Dispose();
                        }
                    }
                });

                InvokeOnStarted(new GameStartedEventArgs());
            }
            else
            {
                try
                {
                    startAction(playRuntime);
                }
                catch (Exception exc) when(!PlayniteEnvironment.ThrowAllErrors)
                {
                    logger.Error(exc, "Play script failed.");
                    InvokeOnStopped(new GameStoppedEventArgs()
                    {
                        SessionLength = Convert.ToUInt64(stopWatch.Elapsed.TotalSeconds)
                    });
                    Dialogs.ShowMessage(
                        exc.Message,
                        LOC.ErrorPlayScriptAction,
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }
                finally
                {
                    if (!playRuntime.IsDisposed)
                    {
                        playRuntime?.Dispose();
                    }
                }
            }
        }
示例#9
0
 public void ExecuteScriptActionPowerShellTest()
 {
     using (var runtime = new PowerShellRuntime("test"))
         ExecuteScriptActionTest(runtime, $"'PowerShell' | Out-File {executeScriptActionTestFileName}");
 }
 /// <summary>
 /// Creates a new instance of <see cref="ParameterSetTests" />.
 /// </summary>
 public ParameterSetTests()
 {
     _powerShellRuntime = new PowerShellRuntime();
     _azContext         = new AzContext(_powerShellRuntime);
 }