Powershell built in commands stopped working - powershell

I need some help trying to troubleshoot my Powershell.
All started when Formatter won't work on newly created file in VS Code.
I restarted all instances of VS Code - and it stopped working everywhere.
I tried to disable and re-install powershell extension - nothing.
VS Code froze on "Starting Powershell.." in bottom right corner and when clicked it says:
Running the contributed command: 'PowerShell.ShowSessionMenu' failed.
When I start Powershell console or Powershell ISE even as Admin, half of the commands not working:
Write-Host : The term 'Write-Host' 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
+ Write-Host "test"
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Write-Host:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Laptop updated to KB4592449 4 days ago and instances of Code and Powershell ISE that I was using normally until today were running since then,
Any idea what happened and how to fix?
Update: Everything returned to norm after I uninstalled Powershell 7 AND PowerToys. Not sure which one helped.
Update2: Nope, after couple of hours same symptoms.
Update3: Troubleshooting further. Ran (Get-Command -type cmdlet Write-Host).ModuleName on a healthy computer, got Microsoft.PowerShell.Utility
Ran Get-Module "Microsoft.PowerShell.Utility" on bad computer - no output, meaning module is not loaded. because on healthy computer it did show some output for that module. Why is not this module imported?
If I say Import-Module Microsoft.PowerShell.Utility on bad computer, Write-Host starts working again.
Why is it not autoloading as always?

Related

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.

Add-MpPreference is not recognized as a name

Hello i am doing a small script will run a small powershell using Add-MpPreference. In my case, i was doing because sometimes i want to include some path's in my windows 10 but i must to do manually. So i was trying to make it automatic. I did this:
ShellExecute("powershell", '-noexit Add-MpPreference -ExclusionPath C:/')
Error return's me:
The term 'Add-MpPreference' is not recognized as the name of a cmdlet, function
, script file, or operable program. Check the spelling of the name, or if a pat
h was included, verify that the path is correct and try again.
At line:1 char:17
+ Add-MpPreference <<<< -ExclusionPath C:/
+ CategoryInfo : ObjectNotFound: (Add-MpPreference:String) [], Co
mmandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
What mean's this error? Or can be fixed?
I had a similar issue. I discovered that when running Powershell in 32 bit mode on a 64 bit OS it doesn't find the command Add-MpPreference.
You can easily recreate this by opening a Powershell console in 32 bit mode and call this function. It will give the same error.
The issue occurred because I was running the Powershell script from C# code that was running as 32 bit. This caused the powershell.exe that was called to also be the 32 bit version.
I adjusted the code to call the 64 bit version and then the command was found.
In order to do this have it run Powershell from here C:\Windows\SysNative\WindowsPowerShell\v1.0\powershell.exe
For more information about how to set the version of powershell visit https://web.archive.org/web/20180314210451/http://www.madwithpowershell.com/2015/06/64-bit-vs-32-bit-powershell.html

Can't find the Connect-ServiceFabricCluster cmdlet when using Powershell

I'm trying to follow this article about deploying a service fabric app through powershell, but I have an issue with running the Connect-ServiceFabricCluster cmdlet. I get the following:
Connect-ServiceFabricCluster : The term 'Connect-ServiceFabricCluster' 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
+ Connect-ServiceFabricCluster
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Connect-ServiceFabricCluster:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Following other articles on the internet, I've tried importing the following things:
Import-Module "$ENV:ProgramW6432\Microsoft SDKs\Service Fabric\Tools\PSModule\ServiceFabricSDK\ServiceFabricSDK.psm1"
Import-Module "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ServiceFabric"
I also saw somewhere to try and set execution policy before importing modules, so I tried this:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force -Scope CurrentUser
In the Modules section of the Powershell ISE I see the ServiceFabricSDK module, but I don't see this cmdlet.
How do I get access to these cmdlets?
Thank you for any help.
Current versions:
Running $PSVersionTable.PSVersion, I get
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
Service Fabric SDK is version 2.5.216
You should make sure you are running the Windows Powershell as opposed to just Powershell. This made a difference for me.
Are you running x86 version of Powershell ISE? I got this error as well but when I switched to the other ISE the cmdlet was available again.
First, I would set your policy to bypass. This can't be done from the script itself, because, well, that's what needs to run with this policy. You could look into setting your powershell ise profile to do this for you.
Set-ExecutionPolicy Bypass
To your question. Not all modules can use the Import-Module feature. For instance, modules from the technet.microsoft.com site must sometimes be manually installed and unzipped. I'm including a script I use below to do this automatically.
#https://www.petri.com/manage-windows-updates-with-powershell-module\
$url = "https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc/file/41459/47/PSWindowsUpdate.zip"
$module = "PSWindowsUpdate"
$zipped = "$($PSScriptRoot)\$($module).zip"
$unzipped = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules"
#$unzipped = "$PSScriptRoot\$($module)"
if (Get-Module -Name $($module)) {
Write-Host "Module exists $($module)"
} else {
Write-Host "Getting Module $($module)"
if(!(Test-Path $zipped)){
(New-Object System.Net.WebClient).DownloadFile($url, $zipped)
if($?){Write-Output "Downloaded zip $($zipped)"}
}else{
Write-Output "Zip found $($zipped)"
}
if(!(test-path "$($unzipped)\$($module)")){
Add-Type -assembly “system.io.compression.filesystem”
[io.compression.zipfile]::ExtractToDirectory($zipped, $unzipped)
if($?){Write-Output "Unzipped to $($unzipped)"}
}
Unblock-File -Path "$($unzipped)\$($module)" -Confirm
if($?){Write-Output "Unblocked file $($unzipped)"}
Import-Module $unzipped\*\$($module).psd1 -Verbose
if($?){Write-Output "Imported module $($unzipped)"}
}
I was too hasty in my first answer. (which is weird, cuz it took awhile to type...) anyhow. It looks like the install process actually unpacks the psm1 for you.
Be sure you are running as admin, use this to check.
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] “Administrator”)
Make sure the file name you made in step 3 matches the path in step 6.
When you run the import module command, follow that up with $?. This will tell you if it imported correctly. You can also use these commands to see if it worked.
get-command -name "Cluster"; get-module
I have just experienced the same problem on my Win10 box,
when cmdlets were not recognized as valid and downloading/installing relevant modules that contained those cmdlets didn't work.
The only solution that worked for me was as follows:
Go to the Control Panel -> "Programs and Features"
Uninstall Service Fabric SDK
click "Turn Windows features on or off" link and uninstall PowerShell
Next, reboot the Windows
Go back to the Control Panel -> "Programs and Features" -> "Turn Windows features on or off"
And install PowerShell
After which download/install Service Fabric SDK
Once again, restart your PC, start the Service Fabric Cluster Manager (if it doesn't auto-start), then right-click its icon on the task-bar and try creating 1-node or 5-node cluster again. In my case, it took less than a minute.

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)