Test to check if Cmdlet is Supported - powershell

I have a powershell script that keeps throwing this error
Get-ComputerRestorePoint : This functionality is not supported on this operating system.
At line:1 char:25
+ Get-ComputerRestorePoint <<<<
+ CategoryInfo : InvalidOperation: (:) [Get-ComputerRestorePoint], ArgumentException
+ FullyQualifiedErrorId : GetComputerRestorePointNotSupported,Microsoft.PowerShell.Commands.GetComputerRestorePoin
tCommand
Is there a simple way to test to see if a cmdlet is supported before running it? I know I can throw a try catch around the cmdlet, but it this approach seems rather expensive compare to a simple check.
Thanks

You can easily check if a cmdlet is available in your session (using Get-Command) but there is not a direct way to test if an available cmdlet supports the current OS. The help notes section for this cmdlet says:
NOTES
To run a Get-ComputerRestorePoint command on Windows Vista and later versions
of Windows, open Windows PowerShell with the "Run as administrator" option.
This cmdlet uses the Windows Management Instrumentation (WMI) SystemRestore
class.
However I wouldn't rely on the Notes being accurate. The best I can think of is what you suggest, use try/catch.

Related

Clojure installed, but clj fails

I installed Clojure via Powershell on Windows 10 and it installed without any errors. When I typed "clj" however, it gave me the following error:
clj : The 'clj' command was found in the module 'ClojureTools', but the module could not be loaded. For more
information, run 'Import-Module ClojureTools'.
At line:1 char:1
+ clj
+ ~~~
+ CategoryInfo : ObjectNotFound: (clj:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CouldNotAutoloadMatchingModule
I installed it to the following location: C:\Program Files\WindowsPowerShell\Modules
How can I resolve this error?
I think you need to do run:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
Because your system does not allow execution of downloaded scripts. Of course decision about how much this is secure for you is completely up to you.
I'd recommend to check this tutorial, written by me:
https://github.com/littleli/scoop-clojure/wiki/Getting-started
It provides alternative, and more convenient way to install Clojure. Also it provides easy path for updates and enables access to a growing amount of utilities that you may find helpful.
Finally. If you have access to Windows Subsystem for Linux (WSL2), I'd probably go in that direction.

Powershell .ps1 scripts won't run / don't exist?

I’ve started having the strangest problem with running powershell scripts in the last few weeks…
They all display this error message as if the file doesn’t exist?
Full console output below showing that I proved the file does exist with the Get-Content cmdlet…
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS H:\> C:
PS C:\> cd C:\Users\Public
PS C:\Users\Public> .\test3.ps1
.\test3.ps1 : The term '.\test3.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.
At line:1 char:1
+ .\test3.ps1
+ ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (.\test3.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Public> get-content test3.ps1
Get-Process | Out-GridView -Wait
PS C:\Users\Public> .\test3.ps1
.\test3.ps1 : The term '.\test3.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.
At line:1 char:1
+ .\test3.ps1
+ ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (.\test3.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Public>
I’ve already got my execution policy set to unrestricted.
Any suggestions
OS
Windows 10 Enterprise
Version 1909 (OS Build 18363.959)
PS C:\Users\Public>> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      5.1.18362.752
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.752
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
UPDATE:
I can get a different result when set to run in PowerShell version 2...
PS C:\Users\Public> powershell -version 2 -ExecutionPolicy bypass -file test3.ps1
Out-GridView : A parameter cannot be found that matches parameter name 'Wait'.
At C:\Users\Public\test3.ps1:1 char:33
+ Get-Process | Out-GridView -Wait <<<<
    + CategoryInfo          : InvalidArgument: (:) [Out-GridView], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.OutGridViewCommand
PS C:\Users\Public> powershell -version 3 -ExecutionPolicy bypass -file test3.ps1
The term 'C:\Users\Public\test3.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.
    + CategoryInfo          : ObjectNotFound: (C:\Users\Public\test3.ps1:String) [], ParentContainsErrorRecordExceptio
   n
    + FullyQualifiedErrorId : CommandNotFoundException
PS C:\Users\Public>
Presumably the -Wait argument just wasn't available in version 2. I can use this now to run scripts in version 2, but obviously that's quite limited functionality.
UPDATE 2:
I had completely forgot that I had this exact problem earlier in the year; and even posted a Question about it over on Superuser…
https://superuser.com/questions/1536086/powershell-wont-run-ps1-files
I had marked up an answer that I thought it was caused by the transition from using CAG to CheckPointVPN (back in March when remote-working was becoming a long-term thing); and it was somehow resolved after going into the office and connecting directly to the network?
This time however; connecting directly to the office network isn’t resolving it.
Only thing else like that that has changed recently; was that IT setup support for Windows Password 30 day resets when working remotely (previously it wasn’t working, so the 30 day reset was previously disabled during lockdown).  I had reset my password remotely just before taking leave in August, and when I came back I was unable to run powershell scripts?
I have tried resetting my password while in the office, but it hasn’t fixed the problem.
I’m stuck for what else I can check??
This problem was down to AppLocker preventing the script from running.
In order to check if this is the cause for your problem, open the Event Viewer and navigate to
> Applications and Services Logs
> > Windows
> > > AppLocker
> > > > MSI and Script
Look for any Error log entries and it should state something like
%OSDRIVE%\USERS\PUBLIC\TEST3.PS1 was prevented from running.
In my case this change was applied by IT security 2 months back; and since then the IT helpdesk have been slowly dealing with the complaints and whitelisting selected folder directories to resolve.
For some reason my colleagues weren't impacted by the change when they should have been; which lead me to believe it was a problem with my machine or user.
In order not to let this question go by without answer, here my comment as answer
Seeing what you have already tried, I think there is a problem with one of the dll's in your system. Since PowerShell is part of Windows 10, you cannot uninstall/reinstall it as far as I know.
What you can try is to repair missing or corrupted system files.
Open an elevated command prompt and run
dism /online /cleanup-image /restorehealth
This will use Windows Update to provide the files that are required to fix corruptions, so an internet connection is required. If that is out of the question, you can specify another source with switch
/Source:<PathToFreshWindowsFiles>
When that finishes, type
sfc /scannow
to scan all protected system files, and replace corrupted files with a cached copy that is located in a compressed folder "%WinDir%\System32\dllcache"
Both actions take quite some time to finish.
When done reboot your computer.
In my case, I had this error and the issue was a file the script was trying to access did not exist. I ran the script in powershell_ise.exe and clicked the Run Script button and a much clearer message was displayed:
Cannot find path 'C:\logs\logfile.log' because it does not exist.
I created the file and the script ran successfully.

Powershell Get-FileMetaData not recognized

I am trying to use the PowerShell command 'Get-FileMetaData' however PowerShell ISE outputs the following error:
Get-FileMetaData : The term 'Get-FileMetaData' 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:1
+ Get-FileMetaData E:\Test_Output
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-FileMetaData:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
The path is correct, I have also tried various existing paths. I cant find anything about what version this command requires, but using $PSVersionTable.PSVersion output states 'Major 5' so I believe I am using PS v5.
Has anyone else had issue with this command? I have found various forums mentioning its function, but cant find much on troubleshooting it.
Thanks for any help!
That is not a core PowerShell cmdlet so I would expect that to fail for most people. As far as I know that comes from the Script Gallery. You need to download that first.
So if you want that to be loaded then take that module will need to be imported either manually or automatically.
You can read more about module loading on MSDN
Using the free tool 'exiftool' I have put together to following script:
$creator = C:\Windows\exiftool.exe "-Creator" $Image.FullName
This allows $creator to be the files Creator which in the case of our production images is the same as the Author.

Powershell 4 Get-ScheduledTask and Windows

I thought no matter what OS you had, if you had Powershell installed, you would have access to the same default cmdlets.
So I want to use Get-ScheduledTask on my Windows 7 machine. I have Powershell 4 installed. However, when I run it, I get the error:
Get-ScheduledTask : The term 'Get-ScheduledTask' 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:1
+ Get-ScheduledTask
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-ScheduledTask:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
If I run on my Windows 8.1 with Powershell 4 already pre-installed along with the OS, it works.
Can I get the cmdlets on my Windows 7 machine? There is nothing on the Microsoft Get-ScheduledTask page about Windows 7 so I am guessing not.
If not then would it be a case of using the command line:
scheduled task command line
No doubt someone will point me at this question but that was for Powershell 2. I am on Powershell 4.
Now I am a big fan of not reinventing the wheel, but this guys scripts look a good alternative.
Get-ScheduledTask relies on underlying features of the OS that Windows 7 doesn't have, so there is no way to run the cmdlet on that OS, even with PowerShell v4. In your case, you can either leverage schtasks.exe or the Schedule.Service COM object.
This answer that you linked gives the best overview of these methods, but in the interests of completeness, I'll link the relevant resources here:
schtasks.exe
MS PowerShellPack TaskScheduler module -> (leverages the Schedule.Service COM object)

file cannot be loaded because the execution of scripts is disabled on this system

File C:\Users\Acer\Desktop\Projelerim\BEM_CANLI\BEM\packages\EntityFramework.5.
0.0\tools\init.ps1 cannot be loaded because its execution is blocked by softwar
e restriction policies. For more information, contact your system administrator.
At line:1 char:44
+ $__pc_args=#(); $input|%{$__pc_args+=$_}; & <<<< 'C:\Users\Acer\Desktop\Proj
elerim\BEM_CANLI\BEM\packages\EntityFramework.5.0.0\tools\init.ps1' $__pc_args[
0] $__pc_args[1] $__pc_args[2]; Remove-Variable __pc_args -Scope 0
+ CategoryInfo : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException
I get above error in package manager console. I found some solution, but I cant fix it. I tried followings
PowerShell says "execution of scripts is disabled on this system."
http://sqlish.com/file-ps1-cannot-be-loaded-because-the-execution-of-scripts-is-disabled-on-this-system-please-see-get-help-about_signing-for-more-details/
I changed execution policy,
But I allways get the same error.
It's possible that you changed the execution policy for 64-bit powershell and the package manager is running 32-bit (or vice versa).
I'd try opening 32-bit console (PowerShell (x86)) and setting the execution policy there, as the error is definitely pointing to that kind of resolution.
Make sure you restart visual studio after changing execution policy so that changes can take effect. Also make sure you changed execution policy globally with administrator username and password.
We have been facing the same issue today with Visual Studio 2017 and Entity Framework 6, and none of the solutions proposed here has worked. As a workaround, this is the temporary solution we found to be able to use Entity Framework commands in the Package Manager Console:
Execute the following commands in the Package Manager Console
Set-ExecutionPolicy -Scope Process Bypass
Import-Module "your-solution-directory/packages/EntityFramework<your EF version>/EntityFramework.psd1"
Actually, the Import-Module command is what the init1.ps1 script does.