Menu
  • HOME
  • TAGS

Is there a way to create a Cmdlet “delegate” that supports pipeline parameter binding?

Tag: powershell,delegates,pipeline,scriptblock

In .NET if you have a subroutine whose implementation might change from one call to another, you can pass a delegate to the method that uses the subroutine. You can also do this in Powershell. You can also use scriptblocks which have been described as Powershell's equivalent of anonymous functions. Idiomatic powershell, however, makes use of powershell's pipeline parameter bindings. But neither delegates nor scriptblocks seem to make use of Powershell's pipeline parameter bindings.

Is there a (idiomatic) way to pass a powershell commandlet to another commandlet in a way that preserves support for pipeline parameter bindings?

Here is a code snippet of what I'd like to be able to do:

Function Get-Square{
    [CmdletBinding()] 
    Param([Parameter(ValueFromPipeline=$true)]$x)
    PROCESS{$x*$x}
}
Function Get-Cube{
    [CmdletBinding()] 
    Param([Parameter(ValueFromPipeline=$true)]$x)
    PROCESS{$x*$x*$x}
}
Function Get-Result{
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline=$true)]$x,$Cmdlet)
    PROCESS{$x | $Cmdlet}
}

10 | Get-Result -Cmdlet {Get-Square}
10 | Get-Result -Cmdlet {Get-Cube}

Best How To :

That'll work. You've just got some syntax issues with your function definitions and how you're passing the parameters:

Function Get-Square{
    [CmdletBinding()] 
    Param([Parameter(ValueFromPipeline=$true)]$x)
    $x*$x
}
Function Get-Cube{
    [CmdletBinding()] 
    Param([Parameter(ValueFromPipeline=$true)]$x)
    $x*$x*$x
}
Function Get-Result{
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline=$true)]$x,$Cmdlet)
    $x | . $cmdlet
}

10 | Get-Result -Cmdlet Get-Square
10 | Get-Result -Cmdlet Get-Cube

100
1000

Get IP address of the Network Adapter of a computer having No gateway

powershell,ip-address,gateway

$configs=gwmi win32_networkadapterconfiguration | where {$_.ipaddress -ne $null -and $_.defaultipgateway -eq $null} if ($configs -ne $null) { $yourtargetIP= $configs[0].IPAddress[0] } # $yourtargetIP will have the IP address to make the gateway from In fact, should you have more than one IPv4 address on your network card, $configs[0].IPAddress will have them all,...

Powershell Invoke-Command with PSCredential Cannot process argument transformation on parameter 'Credential'

powershell,arguments,transformation,credentials,invoke-command

You have a mistake calling ImpersonateSql function. You should not use any parenthesis or commas for specifying parameters when calling function (unless you deliberately want to pass a subexpression or an array as an argument), it's not like C# or javascript function you are used to. Look at an example:...

How to get tableview cell text label from 2nd viewcontroller to a label from 1st viewcontroller?

ios,uitableview,delegates,nsnotifications

1st In VC2, you must create delegate @protocol VC2Delegate; @interface VC2 : UIViewController @property (nonatomic, weak) id <VC2Delegate> delegate; @end @protocol VC2Delegate <NSObject> @required - (void)changeToText:(NSString *)text; @end @implementation VC2 // this is your "完了" action - (IBAction)doneAction:(id)sender { ... [self.delegate changeToText:@"what you want"]; } @end 2nd, add the delegate...

Programmatically accessing TFS history [closed]

c#,.net,powershell,tfs

Shai Raiten's Blog is great for learning the TFS API. For getting file history - read this post: http://blogs.microsoft.co.il/shair/2014/09/10/tfs-api-part-55-source-control-get-history/...

Logging actual error when script fails

powershell,automation,error-logging

Change this: catch { $status = "FAILED" Write-Verbose "`tFailed to Change the administrator password. Error: $_" } to this: catch { $status = "FAILED" Write-Verbose "`tFailed to Change the administrator password. Error: $_" $errmsg = $_.Exception.Message } to preserve the error message(s). And change this: if($Status -eq "FAILED" -or $Isonline...

How to retrieve the name and path of VM's through powercli

powershell

If the text infront and including "Resources" is redundant then using a simple regex we can replacing it before it is output from your function. From $path to $path -replace "^.*?Resources/" So that would replace the similar line inside your function ( Where you return the property). We take everything...

What is the `.` shorthand for in a PowerShell pipeline?

powershell

. is the dot sourcing operator, which runs a script in the current scope rather than a new scope like call operator (i.e. &). That second segment invokes a script block and in that script block defines an advanced function. The advanced function iterates each item in the pipeline and...

Why does piping Get-PSSession to Exit-PSSession not work?

powershell

You've not looked closely enough. Don't forget, it's easy to get all cmdlets related to a certain subject by doing something like this: Get-Help PSSession This gets a list of all cmdlets with "PSSession" it its name. If you carefully review the output, there's Exit-PSSession and Disconnect-PSSession, but there's one...

Error with Get-ADUser: Invalid enumeration context

powershell,active-directory

The biggest issue you have here is you are asking a lot from Get-ADUser. Based on your comment you are pulling in over 900,000 accounts. On top of that you are pulling all properties of those users. There is a touch of insanity there. While I am not perfectly clear...

win32_physicalMemory.Capacity returns null in powershell

windows,powershell

It's because with powershell 2.0 you can't access an array with that method. get-WmiObject win32_physicalMemory -Impersonation 3 -ComputerName "localhost" | select -expand capacity that will work the other powershell 2.0 computers you mention probably only have one stick of memory, so it doesn't return an array...

How do I write a loop to read text file and insert it to the database

sql-server,loops,powershell

To add a simple loop, you can use your existing AutoImportFlatFiles function like this: $Folder= $(read-host "Folder Location ('C:\Test\' okay)") foreach ($file in (get-childitem $Folder)) { $location = split-path $file.FullName -Parent $filename = (split-path $file.FullName -Leaf).split(".")[0] $extension = (split-path $file.FullName -Leaf).split(".")[1] AutoImportFlatFiles -location $location -file $filename -extension $extension -server "WIN123"...

How to create a powershell script that triggers a NuGet Update-Package –reinstall?

powershell,nuget-package

You should run the update command from nuget.exe. One of the parameters of the update command is FileConflictAction, which tells what action to take when asked to overwrite or ignore existing files referenced by the project: overwrite, Ignore, None. You might have to wrap everything in a powershell script, possibly...

CPU usage missing from log for some processes

powershell

You can't get CPU for some processes because of insufficient rights. You get null value then. To output "Nothing" you have to compare the cpu value with $null, something like this: [email protected]{Expression={$_.ProcessName};Label="ProcessName";Width=40},@{Expression={$cpu=$_.CPU;if($cpu -eq $null){"Nothing";} else {$cpu;}};Label="CPU";Width=20} $ServiceTable = @{Expression={$_.Name};Label="Name";Width=40},@{Expression={$_.Status};Label="Status";Width=10} Get-Process | Sort-Object CPU -Descending | Select-Object ProcessName, CPU | format-table...

Color a cell on the basis of another cell value

html,powershell,powershell-v2.0

You should format your HTML result with a different style if there's a condition. To do that, you declare a variable for data style that should be equal to $normalDataStyle if your condition is false, and a special style if it's true. $redDataStyle='style = "border: 1px solid black; background: #c00000;...

Increment Serial Number using EXIF

windows,powershell,command-line,exif,exiftool

You'll probably have to go to the command line rather than rely upon drag and drop as this command relies upon ExifTool's advance formatting. Exiftool "-SerialNumber<001-001-0001-${filesequence;$_=sprintf('%04d', $_+1 )}" <FILE/DIR> If you want to be more general purpose and to use the original serial number in the file, you could use...

Issue filtering out certain event logs from output

html,powershell

I think I see a couple of potential issues. If we have a look at a few event from my local computer. EventID InstanceId Message ------- ---------- ------- 1202 2147484850 Security policies were propagated with warning.... 0 0 The description for Event ID '0' in Source 'gupdate' cannot be found....

PS pipe WorkingSet as variable

variables,powershell

Use Select-Object -ExpandProperty to grab just a single property from the process: $WorkingSet = Get-Process spiceworks |Select-Object -First 1 -ExpandProperty WorkingSet if($WorkingSet -gt 120MB) { # Send email } ...

Why doesn't “go get gopkg.in/…” work while “go get github.com/…” OK?

windows,git,powershell,github,go

The root cause has been found: Because my computer use a web proxy, so I need to set proxy in environment variable: C:\Users\xiaona>set https_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>set http_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 Parsing meta tags from https://gopkg.in/fatih/pool.v2?go-get=1 (status code 200) get "gopkg.in/fatih/pool.v2": found meta tag main.metaImport{Prefix:"gopkg.in/fa tih/pool.v2", VCS:"git",...

Enhancing the pipeline's content?

powershell,powershell-v3.0

Updating archive .\files.zip ... Compressing files.zip ? Check if your function has a case when adding Archive.zip to Archive.zip, this should throw a warning like copying over itself. About pipeline - I think you should employ -passthru switch, if the switch is present, return the archive as a Get-Item result...

Loop Issue - Remote Server

powershell

You never output $DRIVE anywhere, and the expression for $DRIVE shouldn't be in a scriptblock in the first place. The computer name is repeated several times, because you get the SystemName property for each logical disk object. Also, $OS gets the OS name for the local computer, not the remote...

Get list of files whose creation date is greater than some date time

powershell,windows-server-2012

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" | Where-Object { $_.CreationTime -gt [datetime]"2014/05/28" } | Sort-Object CreationTime | Format-Table Name, CreationTime String is cast to datetime if you specify [datetime] before it. You can read about comparison operators by typing help about_Comparison_Operators in PowerShell console....

How to get current working directory inside a Cmdlet

c#,powershell,cmdlet

I am starting in C:\Users\<myusername>. If I know enter cd.. I am in C:\Users\ Entering (Get-Location).Path returns C:\Users. Thats what you want, isnt it? Altrnativly try: WriteObject(this.SessionState.Path.CurrentFileSystemLocation); Reference: How can I get the current directory in PowerShell cmdlet?...

setting up azure ad certificate auth using powershell

powershell,azure,azure-active-directory

The 'value' field for the key credentials is always returned as 'null' for applications and service principals.

PowerShell XML formatting issue

xml,powershell

You're missing a set of parentheses (()) at the end of $XmlWriter.WriteEndElement: $xmlWriter.WriteStartElement("Disk$count") # Add tag for each drive $xmlWriter.WriteElementString("DriveLetter","$DriveLetter") # Write Drive Letter to XML $xmlWriter.WriteElementString("DriveSize","$DriveSize") # Write Drive Size to XML $xmlWriter.WriteElementString("DriveFreeSpace","$DriveFreeSpace") # Write Drive Free Space to XML $xmlWriter.WriteEndElement() # <-- Closing Drive Tag - don't forget...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

Filter and delete Registry values with Where-Object

powershell,registry

I think this issue is a matter of stepping back and taking a look at the bigger picture. You're focused on the value or a property, and how to get that property name that you aren't taking into consideration that the property is just a part of a larger object,...

Get the method name that was passed through a lambda expression?

.net,vb.net,reflection,delegates,pinvoke

I would not do this. It would be simpler to pass a string var representing the error message you want to display or a portion thereof (like the function name). The "simplest" way would be to use an Expression Tree. For this, you would need to change the signature of...

PowerShell Where-Object $_.name -like -in $list

powershell

The Where-Object FilterScript block is just a scriptblock that returns $true, $false or nothing - you can do all kinds of crazy things inside it, including looping over an array to see if there is a wildcard match in one of the entries: Where-Object { $ProductName = $_.Name $_.pscomputername -like...

Send email with body consisting of objects

email,powershell,foreach

Also if you want it to look more nice and readable you can do something like this that will spit it out in a table: $body += "<body><table width=""560"" border=""1""><tr>" $bodyArray[0] | ForEach-Object { foreach ($property in $_.PSObject.Properties){$body += "<td>$($property.name)</td>"} } $body += "</tr><tr>" $bodyArray | ForEach-Object { foreach ($property...

Where is git command after installing “GitHub for Windows”? [closed]

windows,git,powershell,github,github-for-windows

After checking, it should under: %LocalAppData%\GitHub For example, in my PC, it is: C:\Users\xiaona\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin ...

Disconnect Session via Powershell [closed]

session,powershell,user,server,disconnect

Powershell can use normal commands, this one should (according to manual) disconnect a given session: tsdiscon <ID> [/server:PC] [/V] [/VM] Pretty much the same as you use, just the executable is sifferent....

Setting delegates (for protocols) only works in prepareForSegue?

ios,objective-c,delegates,protocols

When instantiated from a storyboard, the initWithCoder: methid is called, not the init method. DestinationViewController *destinationVC = [[destinationViewController alloc] init]; destinationVC.delegate = self; is how you do when your controller is not from a storyboard: you init it from the code. After that you have to manually handle the transition...

Powershell Reading text file

powershell,text,text-files

To read the text after the # characters you must read the file content up to the # characters first. Also, in PowerShell you normally read files either line by line (via Get-Content) or completely (via Get-Content -Raw). You can discard thos parts of the read content that don't interest...

Turn environment variable into an array

powershell

Split the value of the environment variable at whatever delimiter is used. Example: PS C:\> $env:Path C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ PS C:\> $a = $env:Path -split ';' PS C:\> $a C:\WINDOWS\system32 C:\WINDOWS C:\WINDOWS\System32\Wbem C:\WINDOWS\System32\WindowsPowerShell\v1.0\ PS C:\> $a.GetType().FullName System.String[] Edit: The PowerShell equivalent to bash code like this for a in ${MYARR[@]} ; do...

Join SQL query Results and Get-ChildItem Results

sql-server,sql-server-2008,powershell

OK so if the SQL query does not have results then NULL is returned and, in essence, nothing is added to the $dbResults array. Instead lets append the results to a custom object. I don't know what PowerShell version you have so I needed to do something that I know...

View All Certificates On Smart Card

powershell,x509certificate

So, the main problem is actually that you're linking an x86 DLL into a x64 Powershell process. You can check whether your Powershell process is x64 like here (by querying (Get-Process -Id $PID).StartInfo.EnvironmentVariables["PROCESSOR_ARCHITECTURE"]), and if an x64 Powershell detected, start manually a Powershell (x86) located at $env:windir\syswow64\WindowsPowerShell\v1.0\powershell.exe with the same...

How to pass a switch variable?

powershell,parameter-passing

You can use splatting: $xtraOptions = @{} if ($NoPromptForPushPackageToNuGetGallery) { $xtraOptions.Add("NPFPPTNG",$true) } & "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" -Verbose -ProjectFilePath $project -PO "$packOptions" @xtraOptions If $xtraOptions is just an empty hashtable, @xtraOptions will simply have no effect on the parameters passed. You could also push all the parameters into the splatting table...

Extract e-mail from grouped objects

powershell

Your second bit of code hurts my brain, but I think what you want is to output where multiple accounts use the same email address, grouped by email address. So, let's start with getting duplicates. Your first bit of code is kind of functional, but it really collects way more...

PowerShell - Convert CSV to XLSX

powershell

What is the whole "gps" part of the script for? The two (gps excel -ErrorAction SilentlyContinue).count lines at the start and end of the script count the number of Excel executables running. gps is the shorthand alias for get-process. You can find out more by doing help gps which...

Search for certain UPN suffix

powershell,active-directory

You use Get-ADUser and filter on user principal names that end with @sec213.com: $domain = ([adsi]'').distinguishedName $ou = "OU=users,OU=SEC213,OU=Uofguelph,$domain" $suffix = '@sec213.com' Get-ADUser -Filter "userPrincipalName -like '*$suffix'" -SearchBase $ou ...

Create powershell parameter default value is current directory

powershell,powershell-v3.0

Use PSDefaultValue attribute to define custom description for default value. Use SupportsWildcards attribute to mark parameter as Accept wildcard characters?. <# .SYNOPSIS Does something with paths supplied via pipeline. .PARAMETER Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.)....

Using --check on a md5sum command generated checksum file is failing

powershell,cygwin,md5sum

Using the redirection operator to write the checksums to an output file causes the file to be created with the default encoding (Unicode). md5sum expects an ASCII file. Use Set-Content (or Out-File) to save the file with ASCII encoding: md5sum jira_defect.txt | Set-Content result.md5 -Encoding ASCII You can also work...

Remove all folders .old

powershell

Get-ChildItem produces a list of objects. Use a pipeline for processing that list: Get-ChildItem '\\kiewitplaza\vdi\Appsense_profiles' | Where-Object { $_.Name -like '*.old' } | Remove-Item ...

Define an array with prefixes using the range operator

arrays,powershell

Would that do? @(4..9) | % {"usr" + $_} ...

Format a command in powershell including a comma, can't find the right way to escape

powershell,batch-file,escaping,powershell-v2.0,comma

".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" You have double quotes in single quotes in double quotes, so the inner double quotes will terminate the string, so this will be parsed as three values: ".\pacli DELETEUSER DESTUSER='" [email protected]`,com "' sessionid=333" The answer is to escape, with a back tick (`), the inner...

PowerShell logic to remove objects from Array

arrays,powershell

How about not performing a remove, but just sort on tastecode descending and taking just one first result? $DuplicateMembers = $Fruits | Group-Object Name $DuplicateMembers | ForEach-Object { $Outcome = $_.Group | Sort-Object TasteCode -descending | Select -First 1 $Outcome } This way you should not bother to remove anything...

Powershell workflow - Get-Service not filtering

powershell,workflow

I have no idea why -Name [wildcard] works and -DisplayName [wildcard] doesn't (inside a workflow), but you can use Where-Object to accomplish the filtering if you like: workflow Restart-Services{ $services = Get-Service |Where-Object -FilterScript {$_.DisplayName -like "S*"} Foreach -Parallel ($svc in $services){ $name = $svc.Name Restart-Service -Name $name } }...

Get actual path from path with wildcard

powershell,if-statement

Sounds like you want Resolve-Path: if(($Paths = @(Resolve-Path "C:\Test6_*_15.txt"))){ foreach($file in $Paths){ # do stuff } } else { # Resolve-Path was unable to resolve "C:\Test6_*_15.txt" to anything } ...

How do I select a string from a string and replace it in powershell?

powershell

Not the best regex but this would be a good start. You aren't specific about what the line looks like so I will assume that it is on its own line with variable whitespace and or text. Get-ChildItem C:\temp\*.asp | ForEach-Object{ $file = $_.FullName (Get-Content $file) -replace '(.*UserRights\s*)"(.*?)"(.*)','$1("$2")$3' | Set-Content...

Powershell comparison of text file

powershell,readfile

Something to get you started: # $file1 will be an array with each element containing the line contents $file1 = get-content .\text1.txt # $file2 will be an array with each element containing the line contents just like $file1 $file2 = get-content .\text2.txt # This splits each line of $file2 on...