Invoke-Expression, Verbatim Strings, and Invoking Scripts From Other Scripts in PS - c#

I am attempting to call a ps1 script from another ps1 script. These scripts all exist in the same directory. I am able to get a string representing the current directory using the following:
$ScriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent
This works, no problem. To call the secondary script, I am using the Invoke-Expression command, using the above $ScriptDir path and hardcoding the script name (this can be seen at the bottom of this post). However, every time I do this it does a path complaint similar to:
C:\Users\Administrator\Documents\Visual : The term 'C:\Users\Administrator\Documents\Visual' is not recognized as the name of a cmdlet, function, script file, or
operable program.
Normally, in C# this is no problem for me to solve, it is a verbatim string issue. However, I do not see a way to make this work in powershell. For reference, here is a slimmed down version of the completed code I am using to test:
ScriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent
Write-Host "InvocationName:" $MyInvocation.InvocationName
Write-Host "Path:" $MyInvocation.MyCommand.Path
write-host "Starting Test..."
Invoke-Expression "$ScriptDir + \Foo.ps1"
I know I am missing something small.

Instead of
Invoke-Expression "$ScriptDir + \Foo.ps1"
It should be:
& "$ScriptDir\Foo.ps1"

Related

EnumerateFiles Method, UnauthorizedAccessException, and compiling C# in PowerShell [duplicate]

This works to count *.jpg files.
PS C:\> #([System.IO.Directory]::EnumerateFiles('C:\Users\Public\Pictures', '*.jpg', 'AllDirectories')).Count
8
How can an -ErrorAction Continue be applied to this?
PS C:\> #([System.IO.Directory]::EnumerateFiles('C:\Users', '*.jpg', 'AllDirectories')).Count
An error occurred while enumerating through a collection: Access to the path 'C:\Users\Administrator' is denied..
At line:1 char:1
+ #([System.IO.Directory]::EnumerateFiles('C:\Users', '*.jpg', 'AllDire ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I don't think you can. Unless you want to implement directory traversal yourself you're probably stuck with something like this:
Get-ChildItem 'C:\Users' -Filter '*.jpg' -Recurse -Force -ErrorAction SilentlyContinue
Ansgar Wiechers' helpful answer shows a workaround using Get-ChildItem, which is necessary when using the full, Windows-only .NET Framework (FullCLR), on which Windows PowerShell is built.
By contrast, .NET Core v2.1+ - on which PowerShell Core is built - does offer a solution:
#([System.IO.Directory]::EnumerateFiles(
'C:\Users',
'*.jpg',
[System.IO.EnumerationOptions] #{
IgnoreInaccessible = $true
RecurseSubDirectories = $true
}
)).Count
Note that this is the equivalent of -ErrorAction Ignore, not Continue (or SilentlyContinue), in that inaccessible directories are quietly ignored, with no way to examine which of them were inaccessible afterwards.
The solution above is based on this System.IO.Directory.EnumerateFiles() overload, which offers a System.IO.EnumerationOptions parameter.
The above answers work around the issue. They donnot appy the error action.
To realy catch the error action in the .net call, I'm using the $ErrorActionPreference variable in Windows PowerShell, as descirbed in https://devblogs.microsoft.com/scripting/handling-errors-the-powershell-way/:
# Store $ErrorActionPreference
$OldErrorActionPreference = $ErrorActionPreference
# Set $ErrorActionPreference for .net action
# see https://devblogs.microsoft.com/scripting/handling-errors-the-powershell-way/ for other values
$ErrorActionPreference = 'SilentlyContinue'
# .net call
#([System.IO.Directory]::EnumerateFiles('C:\Users\Public\Pictures', '*.jpg', 'AllDirectories')).Count
# restore origional $ErrorActionPreference
$ErrorActionPreference = $OldErrorActionPreference

How can I get the `Suggestion` of PowerShell's Get-Command in C#?

If I create a file called "dir.exe" and run PowerShell command Get-Command dir -Type Application, I get and error because dir is not an application (although that file exists):
gcm : The term 'dir' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:2
+ (gcm dir -Type Application)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (dir:String) [Get-Command], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
Suggestion [3,General]: The command dir was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\dir". See "get-help about_Command_Precedence" for more details.
Notice the Suggestion at the bottom: Suggestion [3,General]: The command dir was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\dir". See "get-help about_Command_Precedence" for more details.
I'm trying to catch that suggestion in my C# code:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Helpers.Tests {
[TestClass]
public class PowerShellRunner_Tests {
[TestMethod]
public void GetCommand_Test() {
// create file called "dir.exe" to see how PowerShell handles
// "Get-Command dir -Type Application":
File.Create("dir.exe").Dispose();
using (PowerShell powerShell = PowerShell.Create()) {
powerShell.AddCommand("get-command")
.AddArgument("dir")
.AddParameter("Type", CommandTypes.Application.ToString());
// run "Get-Command dir -Type Application":
CommandInfo commandInfo = powerShell.Invoke<CommandInfo>().FirstOrDefault();
// get the error:
ErrorRecord error = powerShell.Streams.Error.FirstOrDefault();
// emit the "Suggestion":
Trace.WriteLine(error.ErrorDetails.RecommendedAction);
}
}
}
}
However error.ErrorDetails is null. How can I get that Suggestion?
(I'm trying to get the behavior of where.exe but without the hassle of running a whole process for that).
Given that the end goal is to emulate where.exe's behavior, try the following:
(Get-Command -Type Application .\dir, dir -ErrorAction Ignore).Path
Note the use of -Type Application to limit results to executables and exclude PowerShell-internal commands such as function and aliases.
This will look in the current directory first, as where.exe does.
Give a mere name such as dir, Get-Command doesn't look in the current directory, because PowerShell does not permit invoking executables located in the current directory by name only - for security reasons; using relative path .\, however, makes Get-Command find such an executable.
From cmd.exe, however - whose behavior where.exe assumes - invoking a current-directory-only dir.exe with just dir (by name only) works fine.
If the output is just one path, and that path is a file in the current directory, you can infer that the dir executable exists only in the current directory, which is the condition under which PowerShell emits the suggestion to use an explicit path on invocation.
$fullPaths = (Get-Command -Type Application .\dir, dir -ErrorAction Ignore).Path
$emitSuggestion = $fullPaths.Count -eq 1 -and
(Test-Path ('.\' + (Split-Path -Leaf $fullPaths[0]))
Note: Strictly speaking, you'd also to have rule out the case where the current directory just so happens be one that is listed in $env:PATH:
$env:PATH -split ';' -ne '' -notcontains (Split-Path -Parent $fullPaths[0])
You can report that to your C# code by writing a custom version of the suggestion to the error stream via Write-Error, or, preferably, to the warning stream, with Write-Warning.
To use the above commands via the PowerShell SDK, it's simplest to use the .AddScript() method; e.g.:
powerShell.AddScript("(Get-Command -Type Application .\dir, dir -ErrorAction Ignore).Path");
As for capturing or silencing PowerShell's suggestions:
Unfortunately, you cannot gain access to suggestions programmatically (written as of Windows PowerShell v5.1 / PowerShell Core 6.1.0):
Using the PowerShell SDK, as you do, involves the PowerShell default host, which fundamentally doesn't emit suggestions.
It is only the console host, as used in console (terminal) windows that emits suggestions, but even there suggestions are printed directly to the screen, bypassing PowerShell's system of output streams.
In short: Suggestions only show in console windows (terminals), and can only be viewed, not captured there.
A quick demonstration of the behavior of suggestions in a console window (assumes Windows, with a file named dir.exe in the current dir and not also in $env:PATH):
PS> & { try { Get-Command dir.exe } catch {} } *>$null
Suggestion [3,General]: The command dir.exe was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\dir.exe". See "get-help about_Command_Precedence" for more details.
As you can see, despite the attempt to suppress all output (*>$null), the suggestion still printed to the screen, which also implies that you cannot capture suggestions.
However, there is a way to silence suggestions, namely with -ErrorAction Ignore (PSv3+); by contrast, with -ErrorAction SilentlyContinue the suggestion still prints(!):
PS> & { try { Get-Command dir.exe -ErrorAction Ignore } catch {} } *>$null
# no output

Unable to execute PowerShell script from batch file to run in CMD mode

I created a PowerShell script for FileWatcher. I need to execute it in C#. I tried in many ways but it didn't work. I even created a batch file to execute my script. still it is not working, simply the console gets opened and closed. but when i run each step manually in the command prompt I could able to execute the script.
Below is my PowerShell script:
$folder = 'D:\'
$filter = '*.csv'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property #{
IncludeSubdirectories = $false;
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -Fore red
Out-File -FilePath D:\outp.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"
}
Here is the batch file
D:
powershell.exe
powershell Set-ExecutionPolicy RemoteSigned
./FileWatcherScript
To call a script from Powershell, you should use the -File argument. I'd change your batch file to look something like this - all you need is this one line:
powershell.exe -ExecutionPolicy RemoteSigned -File D:\FileWatcherScript.ps1
Starting powershell.exe without passing any arguments, as in the batch script in your post, will always start an interactive shell that must be exited manually. To run commands through Powershell programatically and exit when finished, you can pass the -File argument as I did above, or the -Command argument which takes a string or script block. Here is a short example of the -Command argument taking a string:
powershell.exe -Command "Invoke-RestMethod https://example.com/api/do/thing; Invoke-RestMethod https://example.com/api/stop/otherthing"
That invocation calls Invoke-RestMethod twice on two different URLs, and demonstrates that you can separate commands with a semicolon (;) to run one after another.
You can also pass a scriptblock to -Command, but note that this only works from within another Powershell session. That looks like this:
powershell.exe -Command { Invoke-RestMethod https://example.com/api/do/thing; Invoke-RestMethod https://example.com/api/stop/otherthing }
That invocation does the same thing as the previous one. The difference is that it is using a scriptblock - a Powershell construct, which again only works if the parent shell is also Powershell - and it's a bit nicer since you have fewer string quoting problems.

Loading a Powershell Module from the C# code of a custom Provider

I've been working on a VERY specific functionality "need" to tie into a custom Provider I'm writing in C#.
Basically I set out to find a way to replicate the
A:
B:
etc functions defined when PowerShell loads so instead of having to type
CD A:
You can just do the aforementioned
A:
I tried first to have my provider inject the functions into the runspace but it seems I'm completely missing the timing of how to get that to work so I went another route.
Basically I have a VERY simple PSM1 file UseColons.psm1
function Use-ColonsForPSDrives
{
[CmdletBinding()] Param()
Write-Verbose "Looping Through Installed PowerShell Providers"
Get-PSProvider | % `
{
Write-Verbose "Found $($_.Name) checking its drives"
$_.Drives | ? { (Get-Command | ? Name -eq "$($_.Name):") -eq $null } | `
{
Write-Verbose "Setting up: `"function $($_.Name):() {Set-Location $($_.Name):}`""
if ($Verbose)
{
. Invoke-Expression -Command "function $($_.Name):() {Set-Location $($_.Name):}"
}
else
{
. Invoke-Expression -Command "function $($_.Name):() {Set-Location $($_.Name):}" -ErrorAction SilentlyContinue
}
Write-Verbose "Finished with drive $($_.Name)"
}
}
# Cert and WSMan do not show up as providers until you try to naviagte to their drives
# As a result we will add their functions manually but we will check if they are already set anyways
if ((Get-Command | ? Name -eq "Cert:") -eq $null) { . Invoke-Expression -Command "function Cert:() {Set-Location Cert:}" }
if ((Get-Command | ? Name -eq "WSMan:") -eq $null) { . Invoke-Expression -Command "function WSMan:() {Set-Location WSMan:}" }
}
. Use-ColonsForPSDrives
In simple terms it loops through all loaded providers, then through all the drives of each provider, then it checks if the Function: drive contains a function matching the {DriveName}: format and if one is not found it creates one.
The psd1 file is nothing more than export all functions
This is stored in the %ProgramFiles%\WindowsPowerShell\Modules path under its own folder
And finally I have profile.ps1 under the %windir%\system32\windowspowershell\v1.0 directory that just does
Remove-Module UseColons -ErrorAction SilentlyContinue
Import-Module UseColons
So when I load PowerShell or the ISE if I want to get to say dir through the variables I can just call
Variable:
Or if I need to switch back to the registry
HKLM:
HKCU:
Which when you are working with multiple providers typing that CD over and over as you switch is just annoying.
Now to the problem I'm still working on developing the actual PowerShell provider this was originally intended for. But when I debug it the UseColons module loads BEFORE visual studio turns around and loads the new provider so if I manually remove and import the module again it does its thing and I have all my drive functions for my provider.
I wanted to know after that LONG explanation how can I either:
Setup my UseColons module to load LAST
Find a way to have my Custom Provider (technically a module since it has the provider AND custom Cmdlets) load the UseColons module when it initializes
I don't want to remove it from my standard profile because it is very helpful when I'm not working on the new provider and just tooling around using powershell for administrative stuff.
Hopefully someone can give me some ideas or point me in the direction of some good deeper dive powershell provider documentations and how-tos.
In your module manifest (.psd1), you have a DLL as the RootModule?
This is a horrible hack, and does not help for drives that get created in the future, but...
In your module manifest, instead of YourProvider.dll as the RootModule, use Dummy.psm1 instead (can be an empty file). Then, for NestedModules, use #( 'YourProvider.dll', 'UseColons' ). This allows the UseColons module to be loaded after YourProvider.dll. (Dummy will be last.)

Include script not working when the powershell script is invoked from C#

I have a power shell script which has include script in it as below.
. "$PSScriptRoot\CheckPermissions.ps1"
When the script is invoked from c#, I am getting this error
{The term '\CheckPermissions.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is
correct and try again.}
The script works fine when run from PS window.
Is not $PSScriptRoot variable available when script is run from c#?
You could try using the following to get the script directory:
$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path
Note that the folder path returned will end with a backslash (\).
Try the below code
$scriptpath = "your second file path"
$psContent = #(Get-Content $scriptPath)
[string]$psCmd = $psContent -join "`n"
$secondscriptoutput = iex $psCmd
$secondscriptoutput #output returned by second file
Myinvocation will not work when ps scripts are invoked from c# code. Please mark this as answer if it works for you. Thanks!

Categories