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
Related
We're executing following commands
...
[System.IO.File]::WriteAllBytes($pathA, $data)
[System.IO.Compression.ZipFile]::ExtractToDirectory($pathA, $pathB)
// OR
Expand-Archive $pathA -DestinationPath $pathB
on Windows 10 Ent. x64 in versions
Name Value
---- -----
PSVersion 5.1.17763.316
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.316
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
The code works unless $pathB happens to be too long. Tried many suggestions found here
\\?\$pathB does work in Explorer but in this code fails in ExtractToDirectory with
The filename, directory name, or volume label syntax is incorrect
and in Expand-Archive with
Cannot process argument because the value of argument "drive" is null.
It shouldn't be a matter of backslash escaping, if I doubled them it gave me
Illegal characters in path
Also tried New-PSDrive as in
New-PSDrive -Name "X" -PSProvider FileSystem -Root $pathBase
but I'm getting
A drive with the name 'X' does not exist.
I read that it needs -Persist, which gives me
...the root must be a file system location on a remote computer.
Tried
net use x: $pathBase
// OR
subst $pathBase "x:\"
Join-Path -Path "x:\" -ChildPath ...
and both end in
Cannot find drive. A drive with the name 'x' does not exist.
Are any of these used wrong? If not - what else to try to fix this?
Thank you
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
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.
I have 3 commands for powershell:
shell.AddScript("Exit-PSSession");
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {some command}");
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {another command}");
Now I don't need any response from the first two, but I need the error log from the third one. Because I can't foresee how many errors may occur, I want to clear the shell from at least all error messages, better would be a complete empty shell.
My solution was this:
shell.AddScript("Exit-PSSession");
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {some command}");
shell.Invoke();
shell.Streams.ClearStreams();
shell.AddScript("Invoke-Command -ComputerName something -ScriptBlock {another command}");
But somehow ClearStreams does nothing at all, shell still knows all old errors and the two previous commands.
The Microsoft sides don't give any more informati0on, than that this method exists and should clear out the shell. (Microsoft Help for ClearStreams) or Microsoft Help for streams in general
Did I miss something, or am I misunderstanding what they
(Powershell is Version 5.0) and C# runs 4.6 NET Framework
Thanks for help in advance.
you can use this:
powershell.Streams.Error();
Sample:
PowerShell powershell = PowerShell.Create();
powershell.Runspace = CreateRunSpace.runspace;
var exec = "Set-Mailbox -Identity John -DeliverToMailboxAndForward $true -ForwardingSMTPAddress 'manuel#contoso.com'";
powershell.AddScript(exec);
powershell.Streams.Error.Clear();
powershell.Streams.Warning.Clear();
var result = powershell.Invoke();
MessageBox.Show(powershell.Streams.Error.Count().ToString()+" error counts");
foreach (var errorRecord in powershell.Streams.Error)
{
MessageBox.Show(errorRecord.ToString()+"first - error");
}
Requesting you to post the full script. What kind of object shell is. I think it will have a method as .Clear()
NOte: I got this :
sh.Commands.AddScript("Add-PSSnapin
Microsoft.SystemCenter.VirtualMachineManager"); sh.Invoke();
sh.Commands.Clear();
Could you please check that
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.)