Skip to content

Import PSDesiredStateConfiguration by name #2062

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ private void RemovePSReadLineForStartup()
{
_logger.Log(PsesLogLevel.Verbose, "Removing PSReadLine");
using SMA.PowerShell pwsh = SMA.PowerShell.Create(RunspaceMode.CurrentRunspace);
bool hasPSReadLine = pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Get-Module", typeof(GetModuleCommand)))
bool hasPSReadLine = pwsh.AddCommand(new CmdletInfo(@"Microsoft.PowerShell.Core\Get-Module", typeof(GetModuleCommand)))
.AddParameter("Name", "PSReadLine")
.Invoke()
.Count > 0;
Expand All @@ -310,7 +310,7 @@ private void RemovePSReadLineForStartup()
{
pwsh.Commands.Clear();

pwsh.AddCommand(new CmdletInfo("Microsoft.PowerShell.Core\\Remove-Module", typeof(RemoveModuleCommand)))
pwsh.AddCommand(new CmdletInfo(@"Microsoft.PowerShell.Core\Remove-Module", typeof(RemoveModuleCommand)))
.AddParameter("Name", "PSReadLine")
.AddParameter("ErrorAction", "SilentlyContinue");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,9 +378,9 @@ await _executionService.ExecutePSCommandAsync(
if (request.RunspaceName != null)
{
PSCommand getRunspaceIdCommand = new PSCommand()
.AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace")
.AddCommand(@"Microsoft.PowerShell.Utility\Get-Runspace")
.AddParameter("Name", request.RunspaceName)
.AddCommand("Microsoft.PowerShell.Utility\\Select-Object")
.AddCommand(@"Microsoft.PowerShell.Utility\Select-Object")
.AddParameter("ExpandProperty", "Id");

try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,17 @@ public static async Task<DscBreakpointCapability> GetDscCapabilityAsync(
if (!isDscInstalled.HasValue)
{
PSCommand psCommand = new PSCommand()
.AddCommand("Import-Module")
.AddArgument(@"C:\Program Files\DesiredStateConfiguration\1.0.0.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psd1")
.AddCommand(@"Microsoft.PowerShell.Core\Import-Module")
.AddParameter("-Name", "PSDesiredStateConfiguration")
.AddParameter("PassThru")
.AddParameter("ErrorAction", ActionPreference.Ignore);

IReadOnlyList<PSModuleInfo> dscModule =
await psesHost.ExecutePSCommandAsync<PSModuleInfo>(
psCommand,
CancellationToken.None,
new PowerShellExecutionOptions { ThrowOnError = false }).ConfigureAwait(false);
new PowerShellExecutionOptions { ThrowOnError = false })
.ConfigureAwait(false);

isDscInstalled = dscModule.Count > 0;
logger.LogTrace("Side-by-side DSC module found: " + isDscInstalled.Value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ public async Task<List<PSCommandMessage>> Handle(GetCommandParams request, Cance
// Executes the following:
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Sort-Object -Property Name
psCommand
.AddCommand("Microsoft.PowerShell.Core\\Get-Command")
.AddCommand(@"Microsoft.PowerShell.Core\Get-Command")
.AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" })
.AddCommand("Microsoft.PowerShell.Utility\\Sort-Object")
.AddCommand(@"Microsoft.PowerShell.Utility\Sort-Object")
.AddParameter("Property", "Name");

IEnumerable<CommandInfo> result = await _executionService.ExecutePSCommandAsync<CommandInfo>(psCommand, cancellationToken).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ public async Task<RunspaceResponse[]> Handle(GetRunspaceParams request, Cancella
rs.Open();
ps.Runspace = rs;
// Returns deserialized Runspaces. For simpler code, we use PSObject and rely on dynamic later.
runspaces = ps.AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace").Invoke<PSObject>();
runspaces = ps.AddCommand(@"Microsoft.PowerShell.Utility\Get-Runspace").Invoke<PSObject>();
}
else
{
PSCommand psCommand = new PSCommand().AddCommand("Microsoft.PowerShell.Utility\\Get-Runspace");
PSCommand psCommand = new PSCommand().AddCommand(@"Microsoft.PowerShell.Utility\Get-Runspace");
// returns (not deserialized) Runspaces. For simpler code, we use PSObject and rely on dynamic later.
runspaces = await _executionService.ExecutePSCommandAsync<PSObject>(psCommand, cancellationToken).ConfigureAwait(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public static async Task<AliasMap> GetAliasesAsync(
// our PSRL on idle handler.
IReadOnlyList<CommandInfo> aliases = await executionService.ExecutePSCommandAsync<CommandInfo>(
new PSCommand()
.AddCommand("Microsoft.PowerShell.Core\\Get-Command")
.AddCommand(@"Microsoft.PowerShell.Core\Get-Command")
.AddParameter("ListImported", true)
.AddParameter("CommandType", CommandTypes.Alias),
cancellationToken).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public static void SetCorrectExecutionPolicy(this PowerShell pwsh, ILogger logge
// We want to get the list hierarchy of execution policies
// Calling the cmdlet is the simplest way to do that
IReadOnlyList<PSObject> policies = pwsh
.AddCommand("Microsoft.PowerShell.Security\\Get-ExecutionPolicy")
.AddCommand(@"Microsoft.PowerShell.Security\Get-ExecutionPolicy")
.AddParameter("-List")
.InvokeAndClear<PSObject>();

Expand Down Expand Up @@ -181,7 +181,7 @@ public static void SetCorrectExecutionPolicy(this PowerShell pwsh, ILogger logge
logger.LogTrace("Setting execution policy to {Policy}", policyToSet);
try
{
pwsh.AddCommand("Microsoft.PowerShell.Security\\Set-ExecutionPolicy")
pwsh.AddCommand(@"Microsoft.PowerShell.Security\Set-ExecutionPolicy")
.AddParameter("Scope", ExecutionPolicyScope.Process)
.AddParameter("ExecutionPolicy", policyToSet)
.AddParameter("Force")
Expand Down Expand Up @@ -222,7 +222,7 @@ public static void LoadProfiles(this PowerShell pwsh, ProfilePathInfo profilePat

public static void ImportModule(this PowerShell pwsh, string moduleNameOrPath)
{
pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module")
pwsh.AddCommand(@"Microsoft.PowerShell.Core\Import-Module")
.AddParameter("-Name", moduleNameOrPath)
.InvokeAndClear();
}
Expand Down
19 changes: 14 additions & 5 deletions src/PowerShellEditorServices/Services/Template/TemplateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ public async Task<bool> ImportPlasterIfInstalledAsync()

IReadOnlyList<PSObject> moduleObject =
await _executionService.ExecutePSCommandAsync<PSObject>(
psCommand, CancellationToken.None).ConfigureAwait(false);
psCommand,
CancellationToken.None,
new PowerShellExecutionOptions { ThrowOnError = false })
.ConfigureAwait(false);

isPlasterInstalled = moduleObject.Count > 0;
_logger.LogTrace("Plaster installed: " + isPlasterInstalled.Value);
Expand All @@ -86,13 +89,19 @@ await _executionService.ExecutePSCommandAsync<PSObject>(

psCommand = new PSCommand();
psCommand
.AddCommand("Import-Module")
.AddCommand(@"Microsoft.PowerShell.Core\Import-Module")
.AddParameter("ModuleInfo", (PSModuleInfo)moduleObject[0].ImmediateBaseObject)
.AddParameter("PassThru");
.AddParameter("PassThru")
.AddParameter("ErrorAction", ActionPreference.Ignore);

IReadOnlyList<PSModuleInfo> importResult = await _executionService.ExecutePSCommandAsync<PSModuleInfo>(psCommand, CancellationToken.None).ConfigureAwait(false);
IReadOnlyList<PSModuleInfo> plasterModule =
await _executionService.ExecutePSCommandAsync<PSModuleInfo>(
psCommand,
CancellationToken.None,
new PowerShellExecutionOptions { ThrowOnError = false })
.ConfigureAwait(false);

isPlasterLoaded = importResult.Count > 0;
isPlasterLoaded = plasterModule.Count > 0;
_logger.LogTrace("Plaster loaded: " + isPlasterLoaded);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ public async Task<string> FetchRemoteFileAsync(
{
// Load the file contents from the remote machine and create the buffer
PSCommand command = new PSCommand()
.AddCommand("Microsoft.PowerShell.Management\\Get-Content")
.AddCommand(@"Microsoft.PowerShell.Management\Get-Content")
.AddParameter("Path", remoteFilePath)
.AddParameter("Raw");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1140,7 +1140,7 @@ await debugService.SetCommandBreakpointsAsync(
VariableDetailsBase var = Array.Find(variables, v => v.Name == "$file");
VariableDetailsBase[] childVars = await debugService.GetVariables(var.Id, CancellationToken.None).ConfigureAwait(true);
Assert.Contains(childVars, i => i.Name is "PSPath");
Assert.Contains(childVars, i => i.Name is "PSProvider" && i.ValueString is "Microsoft.PowerShell.Core\\FileSystem");
Assert.Contains(childVars, i => i.Name is "PSProvider" && i.ValueString is @"Microsoft.PowerShell.Core\FileSystem");
Assert.Contains(childVars, i => i.Name is "Exists" && i.ValueString is "$true");
Assert.Contains(childVars, i => i.Name is "LastAccessTime");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void Dispose()
[Fact]
public async Task CanRegisterAndInvokeCommandWithCmdletName()
{
string filePath = TestUtilities.NormalizePath("C:\\Temp\\Test.ps1");
string filePath = TestUtilities.NormalizePath(@"C:\Temp\Test.ps1");
ScriptFile currentFile = new(new Uri(filePath), "This is a test file", new Version("7.0"));
EditorContext editorContext = new(
editorOperations: null,
Expand Down Expand Up @@ -87,7 +87,7 @@ await psesHost.ExecutePSCommandAsync(
[Fact]
public async Task CanRegisterAndInvokeCommandWithScriptBlock()
{
string filePath = TestUtilities.NormalizePath("C:\\Temp\\Test.ps1");
string filePath = TestUtilities.NormalizePath(@"C:\Temp\Test.ps1");
ScriptFile currentFile = new(new Uri(filePath), "This is a test file", new Version("7.0"));
EditorContext editorContext = new(
editorOperations: null,
Expand Down Expand Up @@ -149,7 +149,7 @@ await psesHost.ExecutePSCommandAsync(
[Fact]
public async Task CanUnregisterCommand()
{
string filePath = TestUtilities.NormalizePath("C:\\Temp\\Test.ps1");
string filePath = TestUtilities.NormalizePath(@"C:\Temp\Test.ps1");
ScriptFile currentFile = new(new Uri(filePath), "This is a test file", new Version("7.0"));
EditorContext editorContext = new(
editorOperations: null,
Expand Down
20 changes: 10 additions & 10 deletions test/PowerShellEditorServices.Test/Session/PathEscapingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ public class PathEscapingTests
[Theory]
[InlineData("DebugTest.ps1", "DebugTest.ps1")]
[InlineData("../../DebugTest.ps1", "../../DebugTest.ps1")]
[InlineData("C:\\Users\\me\\Documents\\DebugTest.ps1", "C:\\Users\\me\\Documents\\DebugTest.ps1")]
[InlineData(@"C:\Users\me\Documents\DebugTest.ps1", @"C:\Users\me\Documents\DebugTest.ps1")]
[InlineData("/home/me/Documents/weird&folder/script.ps1", "/home/me/Documents/weird&folder/script.ps1")]
[InlineData("./path/with some/spaces", "./path/with some/spaces")]
[InlineData("C:\\path\\with[some]brackets\\file.ps1", "C:\\path\\with`[some`]brackets\\file.ps1")]
[InlineData("C:\\look\\an*\\here.ps1", "C:\\look\\an`*\\here.ps1")]
[InlineData(@"C:\path\with[some]brackets\file.ps1", @"C:\path\with`[some`]brackets\file.ps1")]
[InlineData(@"C:\look\an*\here.ps1", @"C:\look\an`*\here.ps1")]
[InlineData("/Users/me/Documents/?here.ps1", "/Users/me/Documents/`?here.ps1")]
[InlineData("/Brackets [and s]paces/path.ps1", "/Brackets `[and s`]paces/path.ps1")]
[InlineData("/CJK.chars/脚本/hello.ps1", "/CJK.chars/脚本/hello.ps1")]
[InlineData("/CJK.chars/脚本/[hello].ps1", "/CJK.chars/脚本/`[hello`].ps1")]
[InlineData("C:\\Animals\\утка\\quack.ps1", "C:\\Animals\\утка\\quack.ps1")]
[InlineData("C:\\&nimals\\утка\\qu*ck?.ps1", "C:\\&nimals\\утка\\qu`*ck`?.ps1")]
[InlineData(@"C:\Animals\утка\quack.ps1", @"C:\Animals\утка\quack.ps1")]
[InlineData(@"C:\&nimals\утка\qu*ck?.ps1", @"C:\&nimals\утка\qu`*ck`?.ps1")]
public void CorrectlyWildcardEscapesPathsNoSpaces(string unescapedPath, string escapedPath)
{
string extensionEscapedPath = PathUtils.WildcardEscapePath(unescapedPath);
Expand All @@ -33,17 +33,17 @@ public void CorrectlyWildcardEscapesPathsNoSpaces(string unescapedPath, string e
[Theory]
[InlineData("DebugTest.ps1", "DebugTest.ps1")]
[InlineData("../../DebugTest.ps1", "../../DebugTest.ps1")]
[InlineData("C:\\Users\\me\\Documents\\DebugTest.ps1", "C:\\Users\\me\\Documents\\DebugTest.ps1")]
[InlineData(@"C:\Users\me\Documents\DebugTest.ps1", @"C:\Users\me\Documents\DebugTest.ps1")]
[InlineData("/home/me/Documents/weird&folder/script.ps1", "/home/me/Documents/weird&folder/script.ps1")]
[InlineData("./path/with some/spaces", "./path/with` some/spaces")]
[InlineData("C:\\path\\with[some]brackets\\file.ps1", "C:\\path\\with`[some`]brackets\\file.ps1")]
[InlineData("C:\\look\\an*\\here.ps1", "C:\\look\\an`*\\here.ps1")]
[InlineData(@"C:\path\with[some]brackets\file.ps1", @"C:\path\with`[some`]brackets\file.ps1")]
[InlineData(@"C:\look\an*\here.ps1", @"C:\look\an`*\here.ps1")]
[InlineData("/Users/me/Documents/?here.ps1", "/Users/me/Documents/`?here.ps1")]
[InlineData("/Brackets [and s]paces/path.ps1", "/Brackets` `[and` s`]paces/path.ps1")]
[InlineData("/CJK chars/脚本/hello.ps1", "/CJK` chars/脚本/hello.ps1")]
[InlineData("/CJK chars/脚本/[hello].ps1", "/CJK` chars/脚本/`[hello`].ps1")]
[InlineData("C:\\Animal s\\утка\\quack.ps1", "C:\\Animal` s\\утка\\quack.ps1")]
[InlineData("C:\\&nimals\\утка\\qu*ck?.ps1", "C:\\&nimals\\утка\\qu`*ck`?.ps1")]
[InlineData(@"C:\Animal s\утка\quack.ps1", @"C:\Animal` s\утка\quack.ps1")]
[InlineData(@"C:\&nimals\утка\qu*ck?.ps1", @"C:\&nimals\утка\qu`*ck`?.ps1")]
public void CorrectlyWildcardEscapesPathsSpaces(string unescapedPath, string escapedPath)
{
string extensionEscapedPath = PathUtils.WildcardEscapePath(unescapedPath, escapeSpaces: true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ await psesHost.ExecutePSCommandAsync(

[Theory]
[InlineData("")] // Regression test for "unset" path.
[InlineData("C:\\Some\\Bad\\Directory")] // Non-existent directory.
[InlineData(@"C:\Some\Bad\Directory")] // Non-existent directory.
[InlineData("testhost.dll")] // Existent file.
public async Task CanHandleBadInitialWorkingDirectory(string path)
{
Expand Down
7 changes: 4 additions & 3 deletions test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -654,20 +654,21 @@ public void DocumentUriReturnsCorrectStringForAbsolutePath()
scriptFile = new ScriptFile(DocumentUri.FromFileSystemPath(path), emptyStringReader, PowerShellVersion);
Assert.Equal("file:///home/NaomiNagata/projects/Rocinate/Proto%3AMole%3Acule.ps1", scriptFile.DocumentUri);

path = "/home/JamesHolden/projects/Rocinate/Proto:Mole\\cule.ps1";
path = @"/home/JamesHolden/projects/Rocinate/Proto:Mole\cule.ps1";
scriptFile = new ScriptFile(DocumentUri.FromFileSystemPath(path), emptyStringReader, PowerShellVersion);
Assert.Equal("file:///home/JamesHolden/projects/Rocinate/Proto%3AMole%5Ccule.ps1", scriptFile.DocumentUri);
}
}

[Trait("Category", "ScriptFile")]
[Theory]
[InlineData("C:\\Users\\me\\Documents\\test.ps1", false)]
[InlineData(@"C:\Users\me\Documents\test.ps1", false)]
[InlineData("/Users/me/Documents/test.ps1", false)]
[InlineData("vscode-notebook-cell:/Users/me/Documents/test.ps1#0001", true)]
[InlineData("https://microsoft.com", true)]
[InlineData("Untitled:Untitled-1", true)]
[InlineData("'a log statement' > 'c:\\Users\\me\\Documents\\test.txt'\r\n", false)]
[InlineData(@"'a log statement' > 'c:\Users\me\Documents\test.txt'
", false)]
public void IsUntitledFileIsCorrect(string path, bool expected) => Assert.Equal(expected, ScriptFile.IsUntitledPath(path));
}
}