How do I ask PowerShell where something is?
For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.
The very first alias I made once I started customizing my profile in PowerShell was 'which'.
New-Alias which get-command
To add this to your profile, type this:
"`nNew-Alias which get-command" | add-content $profile
The `n at the start of the last line is to ensure it will start as a new line.
Here is an actual *nix equivalent, i.e. it gives *nix-style output.
Get-Command <your command> | Select-Object -ExpandProperty Definition
Just replace with whatever you're looking for.
PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe
When you add it to your profile, you will want to use a function rather than an alias because you can't use aliases with pipes:
function which($name)
{
Get-Command $name | Select-Object -ExpandProperty Definition
}
Now, when you reload your profile you can do this:
PS C:\> which notepad
C:\Windows\system32\notepad.exe
I usually just type:
gcm notepad
or
gcm note*
gcm is the default alias for Get-Command.
On my system, gcm note* outputs:
[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
You get the directory and the command that matches what you're looking for.
Try this example:
(Get-Command notepad.exe).Path
My proposition for the Which function:
function which($cmd) { get-command $cmd | % { $_.Path } }
PS C:\> which devcon
C:\local\code\bin\devcon.exe
A quick-and-dirty match to Unix which is
New-Alias which where.exe
But it returns multiple lines if they exist so then it becomes
function which {where.exe command | select -first 1}
I like Get-Command | Format-List, or shorter, using aliases for the two and only for powershell.exe:
gcm powershell | fl
You can find aliases like this:
alias -definition Format-List
Tab completion works with gcm.
To have tab list all options at once:
set-psreadlineoption -editmode emacs
This seems to do what you want (I found it on 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
Check this PowerShell Which.
The code provided there suggests this:
($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe
Try the where command on Windows 2003 or later (or Windows 2000/XP if you've installed a Resource Kit).
BTW, this received more answers in other questions:
Is there an equivalent of 'which' on Windows?
PowerShell equivalent to Unix which command?
If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:
function which($name) {
if ($name) { $input = $name }
Get-Command $input | Select-Object -ExpandProperty Path
}
copy-paste the command to your profile (notepad $profile).
Examples:
❯ echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe
❯ which clang.exe
C:\Program Files\LLVM\bin\clang.exe
I have this which advanced function in my PowerShell profile:
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 }
}
}
Use:
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"
}
Or this version, calling the original where command.
This version also works better, because it is not limited to bat files:
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'
}
You can install the which command from https://goprogram.co.uk/software/commands, along with all of the other UNIX commands.
If you have scoop you can install a direct clone of which:
scoop install which
which notepad
There also always the option of using which. there are actually three ways to access which from Windows powershell, the first (not necessarily the best) wsl -e which command (this requires installation of windows subsystem for Linux and a running distro). B. gnuwin32 which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers option three, install msys2 (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.
There also always the option of using which. there are actually three ways to access which from Windows powershell
The first, (though not the best) is wsl(windows subsystem for linux)
wsl -e which command
This requires installation of windows subsystem for Linux and a running distro.
Next is gnuwin32 which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers
Third, install msys2 (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.
Related
We have been looking at ways that we can scan our code for NuGet packages that have vulnerabilities or are deprecated.
We have looked into using dotnet list package --vulnerable but this doesn't seem to be playing nicely with our Xamarin projects. It throws errors relating to missing project imports and we haven't found a way to get the tools to ignore the errors.
I think the issue is related to this: https://github.com/NuGet/Home/issues/9035
Is it possible to replicate what the CLI tool is doing by calling NuGet APIs?
I have had to check that for an old project of ours that was using packages.config (not supported by dotnet list) This is a powershell function that I have written and it helped in my case:
function Check-Package()
{
param([string]$id ,[string]$version)
$packages = Invoke-RestMethod "https://azuresearch-usnc.nuget.org/query?q=$id"
$packageDetailsUrl = $packages.data | ? { $_.id -eq $id} | %{ $_.versions } | ?{$_.version -eq $version } | %{ $_."#id"}
if($packageDetailsUrl)
{
$packageDetails = Invoke-RestMethod $packageDetailsUrl
$packageSuperDetails = Invoke-RestMethod $packageDetails.catalogEntry
if($packageSuperDetails.vulnerabilities -or $packageSuperDetails.deprecation)
{
if($packageSuperDetails.deprecation)
{
$deprectaion = "is deprecated"
}
if($packageSuperDetails.vulnerabilities)
{
$vulnerability = "has vulnerabilities"
}
Write-Host $id $version $deprectaion $vulnerability
}
}
else
{
Write-Host $id $version no longer listed on nuget.org
}
}
I use it like that:
nuget list -source .\packages\ | %{Check-Package -id $_.Split(" ")[0] -version $_.Split(" ")[1]
I've been working on a PowerShell script that will preserve directory structure when cabbing nested folders. I'm having a bit of difficulty getting the recursion logic right, though.
This is a rough, so there isn't any try/catch error code yet. I've commented out the Remove-Item to prevent accidental runs.
The logic I worked out for this is as follows.
Check & get base tree for subdirectories
Go one level in and check again
Continue until no directories and then return one level up.
Cab directory, remove directory, write log for automated extraction (file names of subdirectory cabs).
Repeat process next level up and continue until base directory
function Chkfordir ($clevel)
{
$dir = dir $clevel | ? { $_.PSIsContainer -eq $true } #Does Current Level have Folders?
if($dir -ne $null) # Yes
{
Chkfordir $dir #Go Deeper
}
if ($dir -eq $null) #Deepest Branch
{
return # Go Back One Level and begin Cabbing
}
$dir | % {
Compress-Directory $_.FullName (".\" + [string]$_.Name + ".cab")
echo ($_.FullName + ".cab" >> .\cleaf.log"
#Remove-Item -Recurse $_.FullName
return
}
}
The function call Compress-Directory is from here.
Edit Changes:
Will Re-Post Code Soon (08/18)
Edit 08/18 So I finally had a chance to test it and the logic seems to work now. There were some problems.
Most of the difficulty came with a powershell gotcha and the unnoticed problem that Compress-Directory is not path independent. Looks like I'll be needing to re-write this function later to be path independent.
The powershell gotcha was in a type change for a value on the pipeline. Apparently after returning from a function directory items are changed from System.IO.FileInfo to System.IO.DirectoryInfo with differently named member functions.
Echo was replaced with Add-Content as the redirection operators don't work in powershell.
There were some unaccounted states to contend with as well. A leaf directory which had no files would cause Compress-Directory to error or complete silently with no file creation (thus not preserving hierarchy).
Solution was to add an Add-Content for leaf folders before return, and moved Add-Content to before the Compress-Directory so there is at least one file in each directory.
I've included my current version below but it is a work in progress.
function Chkfordir ($clevel)
{
$dir = dir $clevel | ? { $_.PSIsContainer -eq $true } # Get Folders?
if ($dir -eq $null) { #Check if deepest branch
Add-Content (Join-Path $_.PSPath "\leaf.log") ([string]$_.FullName + ".cab")
return $_ # Return one level up and cab
}
$dir | % { #for each sub go deeper
Chkfordir $_.FullName
Add-Content (Join-Path $_.PSParentPath "\branch.log") ([string]$_.FullName + ".cab")
Compress-Directory $_.FullName ([string]$_.Name + ".cab")
#Remove-Item $_.FullName -recurse
}
}
You need to recurse for each subdirectory and compress it after the recursive call returns:
function Chkfordir($clevel) {
Get-ChildItem $clevel |
Where-Object { $_.PSIsContainer } |
ForEach-Object {
Chkfordir $_
Compress-Directory ...
...
}
}
That way you automatically descend first, then create the archives as you return.
I am working with Visual Studio 2015 Community with Azure 2.9 For the first time. I tried creating a brand new ASP.Net Web Application. The default template build and viewed in the Browser with no issues.
I tried publishing the site using Azure. When doing so I get this error
The "InvokePowerShell" task failed unexpectedly.
System.Management.Automation.CommandNotFoundException: The term '[cmdletbinding(SupportsShouldProcess=$true)]
param($publishProperties, $packOutput, $nugetUrl)
# to learn more about this file visit http://go.microsoft.com/fwlink/?LinkId=524327
$publishModuleVersion = '1.0.1'
function Get-VisualStudio2015InstallPath{
[cmdletbinding()]
param()
process{
$keysToCheck = #('hklm:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0',
'hklm:\SOFTWARE\Microsoft\VisualStudio\14.0',
'hklm:\SOFTWARE\Wow6432Node\Microsoft\VWDExpress\14.0',
'hklm:\SOFTWARE\Microsoft\VWDExpress\14.0'
)
[string]$vsInstallPath=$null
foreach($keyToCheck in $keysToCheck){
if(Test-Path $keyToCheck){
$vsInstallPath = (Get-itemproperty $keyToCheck -Name InstallDir -ErrorAction SilentlyContinue | select -ExpandProperty InstallDir -ErrorAction SilentlyContinue)
}
if($vsInstallPath){
break;
}
}
$vsInstallPath
}
}
$vsInstallPath = Get-VisualStudio2015InstallPath
$publishModulePath = "{0}Extensions\Microsoft\Web Tools\Publish\Scripts\{1}\" -f $vsInstallPath, $publishModuleVersion
if(!(Test-Path $publishModulePath)){
$publishModulePath = "{0}VWDExpressExtensions\Microsoft\Web Tools\Publish\Scripts\{1}\" -f $vsInstallPath, $publishModuleVersion
}
$defaultPublishSettings = New-Object psobject -Property #{
LocalInstallDir = $publishModulePath
}
function Enable-PackageDownloader{
[cmdletbinding()]
param(
$toolsDir = "$env:LOCALAPPDATA\Microsoft\Web Tools\Publish\package-downloader-$publishModuleVersion\",
$pkgDownloaderDownloadUrl = 'http://go.microsoft.com/fwlink/?LinkId=524325') # package-downloader.psm1
process{
if(get-module package-downloader){
remove-module package-downloader | Out-Null
}
if(!(get-module package-downloader)){
if(!(Test-Path $toolsDir)){ New-Item -Path $toolsDir -ItemType Directory -WhatIf:$false }
$expectedPath = (Join-Path ($toolsDir) 'package-downloader.psm1')
if(!(Test-Path $expectedPath)){
'Downloading [{0}] to [{1}]' -f $pkgDownloaderDownloadUrl,$expectedPath | Write-Verbose
(New-Object System.Net.WebClient).DownloadFile($pkgDownloaderDownloadUrl, $expectedPath)
}
if(!$expectedPath){throw ('Unable to download package-downloader.psm1')}
'importing module [{0}]' -f $expectedPath | Write-Output
Import-Module $expectedPath -DisableNameChecking -Force
}
}
}
function Enable-PublishModule{
[cmdletbinding()]
param()
process{
if(get-module publish-module){
remove-module publish-module | Out-Null
}
if(!(get-module publish-module)){
$localpublishmodulepath = Join-Path $defaultPublishSettings.LocalInstallDir 'publish-module.psm1'
if(Test-Path $localpublishmodulepath){
'importing module [publish-module="{0}"] from local install dir' -f $localpublishmodulepath | Write-Verbose
Import-Module $localpublishmodulepath -DisableNameChecking -Force
$true
}
}
}
}
try{
if (!(Enable-PublishModule)){
Enable-PackageDownloader
Enable-NuGetModule -name 'publish-module' -version $publishModuleVersion -nugetUrl $nugetUrl
}
'Calling Publish-AspNet' | Write-Verbose
# call Publish-AspNet to perform the publish operation
Publish-AspNet -publishProperties $publishProperties -packOutput $packOutput
}
catch{
"An error occurred during publish.`n{0}" -f $_.Exception.Message | Write-Error
}' 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 System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
at System.Management.Automation.PowerShell.EndInvoke(IAsyncResult asyncResult)
at Microsoft.Web.Publishing.Tasks.InvokePowerShell.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() WebApplication1 0
I am assuming I missed something in my install? Anyone know what this error is or how to get passed it?
I upvoted this in the past, then apparently found the answer somewhere else, then forgot the answer again and ended up here again.
Adding <AutoParameterizationWebConfigConnectionStrings>False</AutoParameterizationWebConfigConnectionStrings>
in the csproj on the right PropertyGroup fixed the problem for me.
I have a custom build target in my *.pro file:
docs.commands = doxygen $$PWD/../docs/Doxyfile
QMAKE_EXTRA_TARGETS += docs
POST_TARGETDEPS += docs
which runs Doxygen as a post build event. The problem is, if someone builds the project and hasn't installed doxygen the build fails. Is it possible to check whether or not doxygen is installed on the machine that builds the project so that I run the doxygen command only if doxygen is installed and added to the system PATH?
With qmake, you can try this:
DOXYGEN_BIN = $$system(which doxygen)
isEmpty(DOXYGEN_BIN) {
message("Doxygen not found")
}
Another option could be the following one:
DOXYGEN_BIN = $$system( echo $$(PATH) | grep doxygen )
isEmpty(DOXYGEN_BIN) {
message("Doxygen not found")
}
BTW, if you are using CMake
You can achieve that using
find_package(Doxygen)
Example:
FIND_PACKAGE(Doxygen)
if (NOT DOXYGEN_FOUND)
message(FATAL_ERROR "Doxygen is needed to build the documentation.")
endif()
You have more information in this site:
http://www.cmake.org/cmake/help/v3.0/module/FindDoxygen.html
Try this on your .pro file:
# Check if Doxygen is installed on the default Windows location
win32 {
exists( "C:\Program Files\doxygen\bin\doxygen.exe" ) {
message( "Doxygen exists")
# execute your logic here
}
}
# same idea for Mac
macx {
exists( "/Applications/doxygen.app/ ... " ) {
message( "Doxygen exists")
}
}
Update
Using #Tarod answer you can make it cross compatible with the following
# Check if Doxygen is installed on Windows (tested on Win7)
win32 {
DOXYGEN_BIN = $$system(where doxygen)
isEmpty(DOXYGEN_BIN) {
message("Doxygen not found")
# execute your logic here
} else {
message("Doxygen exists in " $$DOXYGEN_BIN)
}
}
# Check if Doxygen is installed on Linux or Mac (tested on Ubuntu, not yet on the Mac)
unix|max {
DOXYGEN_BIN = $$system(which doxygen)
isEmpty(DOXYGEN_BIN) {
message("Doxygen not found")
# execute your logic here
} else {
message("Doxygen exists in " $$DOXYGEN_BIN)
}
}
Qt docs say:
To obtain the contents of an environment value when qmake is run, use the $$(...) operator...
i.e.:
PATH_VAR = $$(PATH)
DOXYGEN = "doxygen"
contains(PATH_VAR, DOXYGEN) {
message("Doxygen found")
}
How do i find the count of the number of debug statements that is without an if checking?
This is an example of a debug statement that has an if checking:
if(log.isDebug()){
log.debug("This is a debug statement");
}
This is an example of a standalone debug statement that does not have if checking:
log.debug("This is a debug statement");
For example, to find the number of debug statements, i would use this command:
grep -ir "debug" * | wc -l
Here is a simple-minded awk program that tries to find debug statements outside your if guards. Adapt it to count as needed.
/if.*log.isDebug/ {
inif=1
}
/}/ {
inif=0
}
/log.debug/ {
if (!inif) print
}
grep -ir "debug" * | grep -v "if" | wc -l