Powershell windows 10 имя не распознано

PowerShell is a command-line utility for use in Windows that allows some powerful apps and scripts to run. While the GUI is easy to use and gets the job done, a quick script can achieve much more in a much shorter time. If you’re running routines over dozens or hundreds of computers, scripts are a genuine lifesaver.

A ‘cmdlet’ is a script or process that runs within PowerShell, usually denoted by a word, then a hyphen, then another word—for example, Add-Computer or Start-service. Just like everything in Powershell command lines, getting the syntax exactly right is essential.

One thing that all Microsoft products have in common is the notorious error messages when something goes wrong. Rather than speaking in plain English so everyone can understand, Microsoft programs give you some undecipherable gibberish that you need to use Google to comprehend anything at all. The error message, “the term is not recognized as the name of a cmdlet,” in PowerShell, is one such message.

If you know PowerShell already, you easily identify the error that generates the message, “the term is not recognized as the name of a cmdlet.” If you’re new to PowerShell, it may look like gibberish for a while.

Many things can go wrong with a PowerShell command, but three specific ones are the most common: spelling, path, or module issues. When you see the error, “the term is not recognized as the name of a cmdlet,” it will likely be one of those three problems. Lets’ break them down.

1. Check for Spelling Errors in PowerShell

If you spell something wrong, PowerShell won’t be able to understand your instructions and execute them. This scenario is usually the hardest to troubleshoot. Even getting a space wrong can throw PowerShell off. When this situation occurs, it is best to highlight the input text to stand out a little more and then go through it letter by letter.

If there is a lot of text or the highlighting option doesn’t work for you, copy the code into Notepad++ or another plain text editor, and then check it from there. Retype the instructions/code if you don’t see any errors and retry it. Don’t use Word or a rich text editor as it messes around with formatting. Use a plain text editor such as Notepad or Notepad++(recommended).

2. Check for the Wrong Path in PowerShell

If you type the path wrong, PowerShell won’t be able to find your script or module. For example, by pointing PowerShell at a particular folder and inputting the wrong drive letter or a share that isn’t accessible, PowerShell won’t be able to do its thing.

This scenario is often the case when trying to execute a cmdlet on a remote computer. If that computer is locked down or does not allow remotely running specific scripts or changes, it will lead to an error. In most situations, you can cmdlets remotely, but some organizations only allow high-level scripts. Anything that alters security, policies, or core settings gets locked down. In this case, you would need to run the script locally.

You can use “resolve-path” or check the path manually to see if your command is the issue.

3. Check for Missing Modules in PowerShell

If the module is missing or damaged, PowerShell won’t be able to execute it. By default, you have to install modules in the exact order to use them. If that module is missing, corrupt, or got moved, it throws up the error, “the term is not recognized as the name of a cmdlet.”

You can use “get-module” in PowerShell to see if the module is present and correct. It will show you what modules are loaded, and you can add or repair them depending on your needs.

In closing, there is nothing wrong with a newcomer using PowerShell, as long as you’re careful. If you’re using it on a home computer, the worst that could happen is that you need a system restore or rebuild. If you’re working on company computers, you may need to be more careful.

If you are new to using Powershell, don’t be intimidated by it. Create a system restore point before you begin and have a play around. The very worst thing you can do is ruin that Windows installation, but that easily gets remedied for a home user that took precautions first!

Have you ever encountered this error in PowerShell: “the term 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”

If so, this article will help you find out exactly what this error is, what causes it, and how to fix it.

Windows PowerShell prompt

The PowerShell command-line utility and the scripting language is a robust successor to the command prompt utility found on Windows computers. It has a wide range of features and commands (cmdlets) like automating repetitive processes, setting up new machines, forcing Group Policy updates, and allowing coders to control access to numerous files or handle batch files. 

PowerShell also supports various programming constructs like conditional statements, which makes it easy for beginners to create complex scripts. As a result, PowerShell is incredibly popular and useful, but it’s still not without errors.  

If you’re new to PowerShell and you see the particular error we are discussing, here are the things you should know and do.

What Does “The Term ‘_’ Is Not Recognized As the Name of a Cmdlet, Function, Script File, or Operable Program” Mean? 

When you’re greeted with this type of error, it means that PowerShell doesn’t understand the command you’re trying to run. The program is telling you that it can’t find the specific cmdlet, function, script file, or program you’re looking for. 

This error usually occurs because the cmdlet, function, script file, or program you’re trying to use doesn’t exist (due to spelling errors or missing modules). It could also be the case that the cmdlet, function, script file, or program exists, but it’s not in the PowerShell path (incorrect pathing). 

To find out more about these specific causes, move on to the “causes” section below. 

What Do You Mean By The ‘[blank]’ in the PowerShell Error Message? 

When you see the PowerShell error message: 

“The term ‘[blank]’ 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.” 

It means that the ‘[blank]’ is replaced by the cmdlet that is not being recognized. For example, if you’re trying to run something in PowerShell and run is not recognized, it would appear as such:

The term ‘Run’ 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.

Example of Run error

Run: the term ‘run’ 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 iteration of this error message will look different to you than to someone else, as it is based on what you’re trying to do. If you are trying to stop a process instead of trying to run something, the error might read: 

Stop-Process: the term ‘Stop-Process’ 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.”

What Are The Causes Behind the “The Term Is Not Recognized As the Name of a Cmdlet, Function, Script File, or Operable Program” Error Message?

PowerShell is infamous for having obscure error messages, and this is one of them. If you’re new to using the command-line utility and don’t know where to look in your script to find out where you’ve gone wrong, there are 3 common reasons why you get: 

“Term 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.” 

1. Spelling Error(s) in the Cmdlet 

The most common cause for the error is a spelling mistake, either in the cmdlet or the function name. If the name of the cmdlet or function is incorrect, then PowerShell can’t recognize it and throws the error. 

2. Incorrect PowerShell Paths  

When you install PowerShell on Windows, the PowerShell path gets added to the environment variables. The PowerShell path is the location of all the PowerShell-related files and folders on your computer. 

The PowerShell path is important because it tells the command line utility where to look for the cmdlets, functions, script files, and programs you’re trying to use. If these elements aren’t in the path, then PowerShell won’t find it, and you will see this error:

Incorrect PowerShell path can cause the term is not recognized as the name of a cmdlet error

Example of an incorrect path in PowerShell

“Term 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.” 

3. Your Modules Are Missing (Not Imported)  

PowerShell modules are like mini-programs or libraries that you can use to add functionality to the application that isn’t natively available in PowerShell installation.  

Modules are written in PowerShell, and they contain PowerShell functions, cmdlets, variables, and workflows. 

If the cmdlet, function, script file, or program you’re trying to use is contained in a PowerShell module that isn’t imported, then you’ll get the error message: 

missing command - import module example

Example of missing command – import module

“Term 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.” 

6 Ways to Fix the “Term Is Not Recognized As the Name of a Cmdlet, Function, Script File, or Operable Program” Error?

Now that we know the common causes of the error, let’s take a look at the different ways you can fix it. 

Fix #01: Check the Spelling of the Cmdlet or Function Name. 

The first thing you should do when you see the “term 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” error message is to check the spelling of the cmdlet or function name. 

PowerShell is a case-sensitive language, which means the cmdlet or function names have to match exactly the way they’re spelled in the PowerShell installation. If the cmdlet or function name is spelled incorrectly, then PowerShell won’t be able to find it, and you’ll see the error message. 

Fix #02: Verify the PowerShell Paths.

The second thing you should do when you see the said error is to check the PowerShell paths. 

As we mentioned earlier, the PowerShell path is the location of all the PowerShell-related files and folders on your computer. If the cmdlet, function, script file, or program isn’t in the PowerShell path, then the utility won’t be able to find it, and you’ll see the error message we are talking about.

verify path with command to fix the term is not recognized as the name of a cmdlet error message.

To check the PowerShell paths on your computer, you can use the $env:Path variable. This is a built-in PowerShell variable that contains the PowerShell paths. To view the contents of the $env:Path variable, you can use the Get-Content cmdlet:

Get-Content -Path $env:Path

Fix #03: Import the Missing Module.

The third thing you should do when you see the particular error message we are discussing is to import the missing module. As we mentioned earlier, PowerShell modules are like mini-programs or libraries that you can use to extend the functionality of PowerShell. 

If the cmdlet, function, script file, or program you’re trying to use is contained in a PowerShell module that isn’t imported, then you’ll get said error message. 

import module command

To import the missing module, you can use the Import-Module cmdlet. This cmdlet allows you to import PowerShell modules into the current PowerShell session. To use the Import-Module cmdlet, you need to specify the name or path of the module you want to import. For example, to import the Active Directory Module, you can use the following command:

Import-Module -Name Active Directory

Fix #04: Run PowerShell as an Administrator.

The fourth thing you should do when you see the same aforementioned message is to run PowerShell as an administrator. 

Some cmdlets, functions, script files, and programs require administrator privileges to run. If you try to use one of those mentioned without administrator privileges, then you’ll get the error message we’ve been talking about. 

run powershell as administration

To run PowerShell as an administrator, you need to launch the PowerShell application with administrator privileges. To do this, you can right-click the PowerShell shortcut and select “Run as Administrator” from the menu. Alternatively, you can search for PowerShell in the Start menu and select “PowerShell (Run as Administrator)” from the results. 

Fix #05: Restart the PowerShell Session.

The fifth thing you should do when you see the error message in question is to restart the PowerShell session. 

Sometimes, the error message can be caused by a corrupted PowerShell session. To fix this problem, you need to close the session and start a new one.

To close the PowerShell session, you can use the Exit-PSSession cmdlet. This cmdlet closes the PowerShell session and exits the PowerShell console. To start a new PowerShell session, you can launch the PowerShell application again. Alternatively, you can use the New-PSSession cmdlet to create a new PowerShell session.

Fix #06: Uninstall & Reinstall PowerShell. 

Finally, If you’re still seeing the error message, then, you may need to uninstall and reinstall PowerShell. This will delete the PowerShell application and all the cmdlets, functions, script files, and programs associated with it. 

To do this, you can use the Windows PowerShell Uninstall-Application cmdlet. This cmdlet uninstalls an application and all the PowerShell cmdlets associated with the application. After you’ve uninstalled PowerShell, you can reinstall it by downloading the latest PowerShell release from the PowerShell GitHub repository.

Uninstalling and reinstalling PowerShell is a last resort when trying to fix the “term 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” error message. Before you uninstall PowerShell, you should try the other fixes listed in this article. 

Final Words

If this article has helped you fix the PowerShell error problem we discussed, please let us know in the comments below!  

Thanks for reading, and consider sharing this with your friends!

3 min read.

This article explains how I fixed Terminal / PowerShell being unable to locate my winget when I was trying to install something with it. This was quite unexpected as I knew for sure I had installed winget, and I had also used it before successfully.

But alas, things break down and need fixing. And here’s how to fix this particular issue.

Problem

Table of Contents

Let’s take a quick look at the actual problem first. Imagine this: You’re trying to install or update something using winget using PowerShell, Terminal, command line, bash or some other flavor of a command-line interpreter, but you run into this error:

winget: The term 'winget' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

If that’s the exact error you’re getting, chances are the reason is quite simple. You either don’t have winget, or your flavor of command-line interpreter doesn’t know how to find the executable winget.exe.

Reason

For whatever reason, winget installs without modifying the Path environment variable to include the, well, path to the winget executable. Or at least it might.

And while it MIGHT actually add the path to the executable, that path might be version-specific – and after winget getting updated itself, that path changes. And you won’t have winget anymore.

Ah well. A lot of weird things have happened to MY winget installation for sure. But let’s take a look at the couple of different ways how to fix it.

Solution

Time needed: 10 minutes

How to fix “The term ‘winget’ is not recognized as a name of a cmdlet, function, script file, or executable program.” in Windows 10?

  1. Verify winget alias is enabled

    This was a funny one – didn’t even know this could be broken!

    Verify that “winget” alias is enabled for use in different Windows apps. Do this by searching for “Manage app execution aliases” in Start menu:

    Then make sure winget is enabled:

    And here’s a demonstration on how this affects Windows Terminal – 2 first tries the alias was turned off, for the last one it was enabled:

  2. Add all Windows Apps to your PATH at once

    Add this to your environment variable “PATH” – or make sure that it is there already.

    %UserProfile%\AppData\Local\Microsoft\WindowsApps.

    This is kind of a no-brainer – even if you don’t have winget installed, this should probably be set up. Might fix some other apps that you didn’t yet know were broken.

    That said…

  3. Install or update your winget

    Okay, this might sound stupid, but it might make sense to double-check you have installed winget in the first place. While having a command-line interface to Microsoft Store really does make sense (not only for automation use cases, but also for being able to actually install something whenever the Microsoft Store UI is broken again as it sometimes is), I don’t think it is automatically installed with Windows out-of-the-box.

    You can make sure you have the latest version of winget installed by searching for “winget” or “App Installer” in Microsoft Store, if you’re crazy enough to try and use it.

    I’m sure it’ll load any moment now. Any moment now.

    If you get tired of waiting for Microsoft Store to load, check out the next step.

  4. Install or reinstall winget

    If you don’t have 4 hours to wait for the Store to load, you might want to download the latest file from the apps GitHub repository instead.

    That would be here: https://github.com/microsoft/winget-cli/releases

    After downloading the appropriate latest version of the “App Installer” installer, reinstall it. You’ll see something like below, but that’s to be expected:

  • Author
  • Recent Posts

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That’s definitely enough funny buzzwords!), who works as Solutions Architect for Precio Fishbone, building delightful Digital Workplaces.

He’s been a developer from 2004 (starting with PHP and Java), and he’s been working on .NET projects, Azure, Office 365, SharePoint and a lot of other stuff. He’s also Microsoft MVP for Azure.

This is his personal professional (e.g. professional, but definitely personal) blog.

все правильно, у тебя в скрипте нарушена логика.
при запуске скрипта из конфигуратора у тебя все переменные сохраняются, а когда ты скрипт запускаешь все переменные перезадаються за ново, в итоге в логике сктрипта у тебя сперва стартует поиск а потом задаються переменные, конечно искать ему нечего.
сперва задай переменные а только потом запускай процедуру поиска.

Добавлено через 10 минут
все правильно, у тебя в скрипте нарушена логика.
при запуске скрипта из конфигуратора у тебя все переменные сохраняются, а когда ты скрипт запускаешь все переменные перезадаються за ново, в итоге в логике сктрипта у тебя сперва стартует поиск а потом задаються переменные, конечно искать ему нечего.
сперва задай переменные а только потом запускай процедуру поиска.

1. Задай массив. его у тебя нет. у тебя в массиве как ты считаешь только пути.

PowerShell
1
2
3
4
5
6
7
$dire = "C:\Test","C:\Test2"
# Получаем дату начала дня.
$date = (Get-Date).Date
write-host $date
 
[B]Задаешь массив для обработки:[/B]
$files = Get-ChildItem -Path $item | Where {$_.LastWriteTime -ge "$date"}

и если тебе нужны только файлы то зачем тебе всё содержимое директории.
используй Where-Object.

и добавить проверку доступности путей через
Test-Path:
сейчас не когда весь код проверять, но сам попробуй, если не получиться то я в понедельник отпишусь.
и задачу опиши полностью что тебе нужно получить, потому как не понятно зачем тебе файловая проверка, причем не ясно.
на первый взгляд очень много вопросов.

Вообще я редко вижу смысл в том чтобы отлавливать ошибки в скриптах, но недавно ко мне попалась задача, где необходимо было обработать ошибки в скрипте PowerShell. Дело в том что данный скрипт использовался как часть работы System Center Orchestrator. Для этого я использовал Try/Catch/Finaly . Но все по порядку.

Немного про ошибки

Ошибки можно условно разделить на две больших категории.

  1. Прерывающие
  2. Не прерывающие

Первые завершают выполнение конвейера с ошибкой. Т.е. дальнейшие команды в конвейере не выполняются. Например, вы не правильно указали имя команды. Вторая категория лишь генерирует ошибку, но конвейер продолжает выполняться далее. Например, вы запросили содержимое не существующего каталога.

В любом случае всю информацию о всех ошибках можно поглядеть в переменной $error. Последняя ошибка идет с индексом 0, т.е. $error[0] — покажет последнюю ошибку. А $error[0].Exception описание последней ошибки.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

PS C:\> Get-Command NoCommand,Dir

Get-Command : Имя «NoCommand» не распознано как имя командлета, функции, файла сценария или выполняемой программы. Пров

ерьте правильность написания имени, а также наличие и правильность пути, после чего повторите попытку.

строка:1 знак:1

+ Get-Command NoCommand,Dir

+ ~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (NoCommand:String) [Get-Command], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

CommandType     Name                                               ModuleName

                                                   

Alias           dir -> Get-ChildItem

PS C:\> $error[0]

Get-Command : Имя «NoCommand» не распознано как имя командлета, функции, файла сценария или выполняемой программы. Пров

ерьте правильность написания имени, а также наличие и правильность пути, после чего повторите попытку.

строка:1 знак:1

+ Get-Command NoCommand,Dir

+ ~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (NoCommand:String) [Get-Command], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand

PS C:\> $error[0].Exception

Имя «NoCommand» не распознано как имя командлета, функции, файла сценария или выполняемой программы. Проверьте правильн

ость написания имени, а также наличие и правильность пути, после чего повторите попытку.

Этот же пример, но в виде рисунка для наглядности.

Переменная Error

Для того чтобы выяснить была ли в какой-то части кода ошибка необходимо использовать Try. Это помогает избавиться от неожиданного и некорректного завершение вашего скрипта. Позволяя так же корректно завершить его работу.

Синтаксис выглядит в общем случае так.

Try

{

  часть кода в которой ищем ошибку

}

Catch

{

[тип ошибки, которую ищем] код,

     который будет выполнен когда ошибка будет найдена

}

Finally

{

код, который будет выполнен в любом случае

}

Однако использование Finally и определение типа ошибки — опционально и может не использоваться.

Для проверки напишем вот такой код где используем Try в PowerShell для того чтобы обработать ошибку деления на ноль и вывести информацию об ошибке.

try

{

[float](4/0)

}

catch

{

  Write-Host «Error!!!»

  Write-Host $error[0].Exception

}

Как видно я произвожу деление на ноль в блоке try, т.е. совершаю прерывающую ошибку. Только прерывающие ошибку будут отловлены. А далее в блоке catch произвожу уже необходимые отладочные действия, т.е. произвожу обработку ошибки.. В моей исходной задаче я в данном блоке заносил информацию об ошибках в специальный лог файл, но давайте попробуем запустить мой данный пример.

PS C:\> .\test.ps1

Error!!!

System.Management.Automation.RuntimeException: Попытка деления на нуль. -> System.DivideByZeroException: Попытка делен

ия на нуль.

   Конец трассировки внутреннего стека исключений

   в System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exce

ption)

   в System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)

   в System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

   в System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

Увы в блоке try в PowerShell должна присутствовать прерывающая ошибка.

Преобразуем не прерывающую ошибку в прерывающую

Существует общий параметр для всех командлетов в PowerShell -ErrorAction. Данный параметр может принимать четыре значения

  • Continue — выводит ошибку и продолжает выполнение
  • SilentlyContinue — не выводит ошибку и продолжает выполнение
  • Stop — завершает выполнение
  • Inquire — спрашивает у пользователя как поступить

В нашем случае подходит действие stop. Если использовать параметр со значением -ErrorAction Stop, то при возникновении ошибки при выполнении команды, данная ошибка прерывает выполнение команды. Ниже пример скрипта, использующего -ErrorAction Stop.

try

{

  Dir NoFolder -ErrorAction Stop

}

catch

{

  Write-Host «Error!!!»

  Write-Host $error[0].Exception

}

Ниже результат выполнения данного скрипта

PS C:\> .\test.ps1

Error!!!

System.Management.Automation.ItemNotFoundException: Не удается найти путь «C:\NoFolder»,

так как он не существует.

   в System.Management.Automation.SessionStateInternal.GetChildItems(String path, Boolean recurse, C

mdletProviderContext context)

   в Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord()

В моей исходной задаче try в PowerShell необходимо было использовать для всех команд в скрипте. Поскольку обработка ошибки была общей для любой ошибки в скрипте весь скрипт можно поместить в один Try, конечно это не совсем правильно, но зато просто. Чтобы каждый раз не писать -ErrorAction Stop. Можно воспользоваться переменной $ErrorActionPreference, которая имеет те же значения и сходна по действию, однако распространяет свое действие на все командлеты в скрипте.

$ErrorActionPreference = «stop»

try

{

  Dir Folder

  Get-Process -ComputerName TestPC

}

catch

{

  Write-Host «Error!!!»

  Write-Host $error[0].Exception

}

Вместо заключения

Конечно, по началу вы мало будете задумываться об поиске ошибок, используя множество условных конструкций вы их минимизируете. Однако использование try в PowerShell позволит минимизировать случаи неожиданного завершения скрипта.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Через что открывать rar на windows 10
  • Замена меню пуск windows 11 на windows 7
  • Разрешить подключение устройства bluetooth не активно windows 11
  • Jdk 8u311 windows x64 exe
  • Как посмотреть какие приложения запускались в windows 10