我正在尝试编写一个PowerShell函数,我可以使用它来管理非PowerShell命令。例如,而不是:
$(document).on('ready page:load', function () {
// Actions to do
});
我想这样做:
dir -r *.js | % { git checkout -- $_.FullName }
或类似的东西。现在我有以下代码不起作用:
dir -r *.js | pipe git checkout --
你会怎么写这个,或者有什么建议的方法吗?
答案 0 :(得分:0)
这就是我最终做的事情:
# Use this cmdlet to pipe files to regular commands
# Example:
# dir -r *.js | select -first 3 | pipe atom
# dir -r *.js | select -first 3 | %% devenv _ /edit
# dir -r *.js | select -first 3 | %% git checkout
function Pipe-Command
{
[CmdletBinding()]
PARAM(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[IO.FileInfo[]]$File,
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true, Position=0)]
[string]$Command,
[switch]$WhatIf
)
BEGIN
{
if ($Command -match '^git ' -and !$Command.Trim().EndsWith(' _')) {
$Command += ' --';
}
}
PROCESS
{
$QuotedPath = "`"$($file.FullName)`""
if ($Command -cmatch ' _ ') {
$CommandToRun = $Command.Replace(' _ ', " $QuotedPath ")
}
else {
$CommandToRun = "$Command $QuotedPath"
}
if ($WhatIf) {
Write-Host "What if: $CommandToRun"
}
else {
if (Get-Command Write-Information) {
Write-Information $CommandToRun
}
Invoke-Expression $CommandToRun
}
}
END {}
}
Set-Alias pipe Pipe-Command
Set-Alias %% Pipe-Command