В числовом программном обеспечении есть случаи, когда вы хотите проверить, равно ли два числа с плавающей запятой в точности . Я разместил это по аналогичному вопросу
https://stackoverflow.com/a/10973098/1447411
Таким образом, вы не можете сказать, что «CompareDoubles1» вообще-то неправильно.
Проверьте этот Powershell, который
Предоставленный здесь код предлагает это
($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe
class Program
{
delegate void D1();
delegate string D2();
static string X() { return null; }
static void Y(D1 d1) {}
static void Y(D2 d2) {}
static void Main()
{
Y(X);
}
}
Чтобы добавить это в свой профиль, введите: void Q(Expression<Func<string>> f){}
string M(int x) { ... }
...
int y = 123;
Q(()=>M(y++));
`n должен гарантировать, что он будет начинаться как новая строка. Быстрое совпадение с Unix which
-
New-Alias which where.exe
Но он возвращает несколько строк, если они существуют, поэтому он становится
$(where.exe command | select -first 1)
U+0000 .. U+007F 1 byte 0xxx xxxx
U+0080 .. U+07FF 2 bytes 110x xxxx 10xx xxxx
U+0800 .. U+FFFF 3 bytes 1110 xxxx 10xx xxxx 10xx xxxx
U+10000 .. U+10FFFF 4 bytes 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
должен сказать вам char16_t
– Chris F Carroll
8 April 2017 в 19:07
where.exe
эквивалентно which -a
, так как он вернет обратно all i> соответствие исполняемым файлам, а не только первый, который будет выполнен. То есть, where.exe notepad
дает c:\windows\notepad.exe
и c:\windows\system32\notepad.exe
. Так что это особенно not i>, подходящее для формы $(which command)
. (Еще одна проблема заключается в том, что он напечатает приятное, полезное сообщение об ошибке, если команда не будет найдена, которая также не будет хорошо расширяться в $()
- которая может быть исправлена с помощью /Q
, но не как псевдоним.)
– Jeroen Mostert
5 March 2018 в 17:53
Попробуйте выполнить команду where
в Windows 2003 или более поздней версии (или Windows 2000 / XP, если вы установили Resource Kit): http://ss64.com/nt/where.html
BTW, это получило больше ответов в других потоках:
where
в командную строку Where-Object
в Powershell, поэтому ввод текста where <item>
в командной строке Powershell ничего не дает. Таким образом, этот ответ совершенно неверен - как указано в принятом ответе в первом связанном вопросе, чтобы получить DOS where
, вам нужно ввести where.exe <item>
.
– Ian Kemp
1 July 2015 в 15:09
Обычно я просто набираю:
gcm notepad
или
gcm note*
gcm является псевдонимом по умолчанию для Get-Command.
В моей системе, gcm note * выходы:
[27] » gcm note*
CommandType Name Definition
----------- ---- ----------
Application notepad.exe C:\WINDOWS\notepad.exe
Application notepad.exe C:\WINDOWS\system32\notepad.exe
Application Notepad2.exe C:\Utils\Notepad2.exe
Application Notepad2.ini C:\Utils\Notepad2.ini
Вы получаете каталог и команду, которые соответствуют тому, что вы ищете.
gcm note* | select CommandType, Name, Definition
. Если вы часто запускаете его, вы должны, вероятно, включить его в функцию.
– David Mohundro
28 November 2016 в 19:04
У меня есть эта расширенная функция which
в моем профиле PowerShell:
function which {
<#
.SYNOPSIS
Identifies the source of a PowerShell command.
.DESCRIPTION
Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable
(which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in
provided; aliases are expanded and the source of the alias definition is returned.
.INPUTS
No inputs; you cannot pipe data to this function.
.OUTPUTS
.PARAMETER Name
The name of the command to be identified.
.EXAMPLE
PS C:\Users\Smith\Documents> which Get-Command
Get-Command: Cmdlet in module Microsoft.PowerShell.Core
(Identifies type and source of command)
.EXAMPLE
PS C:\Users\Smith\Documents> which notepad
C:\WINDOWS\SYSTEM32\notepad.exe
(Indicates the full path of the executable)
#>
param(
[String]$name
)
$cmd = Get-Command $name
$redirect = $null
switch ($cmd.CommandType) {
"Alias" { "{0}: Alias for ({1})" -f $cmd.Name, (. { which cmd.Definition } ) }
"Application" { $cmd.Source }
"Cmdlet" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"Function" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"Workflow" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"ExternalScript" { $cmd.Source }
default { $cmd }
}
}
function Which([string] $cmd) {
$path = (($Env:Path).Split(";") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName
if ($path) { $path.ToString() }
}
# check if Chocolatey is installed
if (Which('cinst.bat')) {
Write-Host "yes"
} else {
Write-Host "no"
}
Или эту версию, вызывая команду оригинала где. Эта версия также работает лучше, потому что не ограничивается файлами bat
function which([string] $cmd) {
$where = iex $(Join-Path $env:SystemRoot "System32\where.exe $cmd 2>&1")
$first = $($where -split '[\r\n]')
if ($first.getType().BaseType.Name -eq 'Array') {
$first = $first[0]
}
if (Test-Path $first) {
$first
}
}
# check if Curl is installed
if (which('curl')) {
echo 'yes'
} else {
echo 'no'
}
Мне нравится get-command | format-list или:
gcm powershell | fl
Вы можете найти такие псевдонимы:
alias -definition format-list
Выполнение вкладок работает с gcm.
Мое предложение для какой функции:
function which($cmd) { get-command $cmd | % { $_.Path } }
PS C:\> which devcon
C:\local\code\bin\devcon.exe
Это похоже на то, что вы хотите (я нашел его на http://huddledmasses.org/powershell-find-path/ )
Function Find-Path($Path, [switch]$All=$false, [Microsoft.PowerShell.Commands.TestPathType]$type="Any")
## You could comment out the function stuff and use it as a script instead, with this line:
# param($Path, [switch]$All=$false, [Microsoft.PowerShell.Commands.TestPathType]$type="Any")
if($(Test-Path $Path -Type $type)) {
return $path
} else {
[string[]]$paths = @($pwd);
$paths += "$pwd;$env:path".split(";")
$paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
if($paths.Length -gt 0) {
if($All) {
return $paths;
} else {
return $paths[0]
}
}
}
throw "Couldn't find a matching path of type $type"
}
Set-Alias find Find-Path
Вот фактический эквивалент * nix, т. е. он дает выход * nix-стиля.
Get-Command <your command> | Select-Object -ExpandProperty Definition
Просто замените все, что вы ищете.
PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe
Когда вы добавите его в свой профиль, вы захотите использовать функцию, а не псевдоним, потому что вы не можете использовать псевдонимы с трубами:
function which($name)
{
Get-Command $name | Select-Object -ExpandProperty Definition
}
Теперь, когда вы перезагружаете свой профиль, вы можете сделать это :
PS C:\> which notepad
C:\Windows\system32\notepad.exe
Попробуйте этот пример:
(Get-Command notepad.exe).Path
Get-Command <command> | Format-Table Path, Name
, поэтому я могу получить путь, в котором сидит команда. – jrsconfitto 27 November 2012 в 17:17select -expandproperty Path
. – Casey 29 July 2015 в 12:37