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

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.

Related

Powershell built in commands stopped working

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?

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

The term 'cpdf' is not recognized as the name of a cmdlet, function, script file, or operable program

I have downloaded CPDF because I have to batch work on a large number on PDFs.
The executable is on my Desktop: C:\Users\admin\Desktop\cpdf.exe
I am running PowerShell ISE on Windows 7 as Administrator. I have set Set-ExecutionPolicy Unrestricted.
My prompt is at the desktop location: PS C:\Users\ftsadmin\Desktop> but if I try to run cpdf: PS C:\Users\ftsadmin\Desktop> cpdf or as PS C:\Users\ftsadmin\Desktop> cpdf.exe, I get the following error:
The term 'cpdf.exe' 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:9
+ cpdf.exe <<<<
+ CategoryInfo : ObjectNotFound: (cpdf.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I don't understand. When I am doing exactly the same in my Windows XP VM, it works (but I prefer Windows 7+ because of the PowerShell ISE).
Any ideas what I'm missing?
Unlike CMD PowerShell does not automatically include the current directory in the search path (it behaves like Unix shells in this respect). To run a program or script from the current directory you need to use the relative or absolute path:
.\cpdf.exe
C:\Users\ftsadmin\Desktop\cpdf.exe
The execution policy has nothing to do with this, as it governs only the execution of PowerShell scripts, not of external commands.

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)

The term 'get-splogevent' is not recognized as the name of a cmdlet

I'm new to Sharepoint... and I'm trying to deploy a simple web part.
When I do deploy it and place it on a page, I get an error with a correlation id.
Now, I'm trying to get details about the error, and using Powershell I type...
get-splogevent | ?{$_Correlation -eq "bcce1b39-f277-4b2b-b8f8-4c113a30f193" }
But it's giving me an error....
The term 'get-splogevent' 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:15
+ get-splogevent <<<< | ?{$_Correlation -eq "bcce1b39-f277-4b2b-b8f8-4c113a30f193" }
+ CategoryInfo : ObjectNotFound: (get-splogevent:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Any ideas as to what I'm doing wrong?
Most likely you are on an ordinary Powershell session. The Sharepoint management snap-in is not being loaded, so cmdlet is not found. Take a look at an article that describes how to load the snap-in automatically to all Powershell sessions.
The snap-in is loaded manually like so,
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
I was starting the solo powershell instead of the sharepoint one. In the task bat there is "Sharepoint 2010 Management Shell", using that worked.