scriptblock

For PowerShell cmdlets, can I always pass a script block to a string parameter?

为君一笑 提交于 2019-11-27 05:32:33
I'm looking at the document of Rename-Item and there is an example like this. PS C:\>Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt','.log' } This example shows how to use the Replace operator to rename multiple files, even though the NewName parameter does not accept wildcard characters. This command renames all of the .txt files in the current directory to .log. The command uses the Get-ChildItem cmdlet to get all of the files in the current folder that have a .txt file name extension. Then, it uses the pipeline operator (|) to send those files to Rename-Item . The

Pass arguments to a scriptblock in powershell

我与影子孤独终老i 提交于 2019-11-27 01:55:34
I guess you can't just do this: $servicePath = $args[0] if(Test-Path -path $servicePath) <-- does not throw in here $block = { write-host $servicePath -foreground "magenta" if((Test-Path -path $servicePath)) { <-- throws here. dowork } } So how can I pass my variables to the scriptblock $block? Lars Truijens Keith's answer also works for Invoke-Command , with the limit that you can't use named parameters. The arguments should be set using the -ArgumentList parameter and should be comma separated. $sb = {param($p1,$p2) $OFS=','; "p1 is $p1, p2 is $p2, rest of args: $args"} Invoke-Command $sb

For PowerShell cmdlets, can I always pass a script block to a string parameter?

情到浓时终转凉″ 提交于 2019-11-26 11:37:05
问题 I\'m looking at the document of Rename-Item and there is an example like this. PS C:\\>Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace \'\\.txt\',\'.log\' } This example shows how to use the Replace operator to rename multiple files, even though the NewName parameter does not accept wildcard characters. This command renames all of the .txt files in the current directory to .log. The command uses the Get-ChildItem cmdlet to get all of the files in the current folder that have a

Pass arguments to a scriptblock in powershell

时光毁灭记忆、已成空白 提交于 2019-11-26 09:50:02
问题 I guess you can\'t just do this: $servicePath = $args[0] if(Test-Path -path $servicePath) <-- does not throw in here $block = { write-host $servicePath -foreground \"magenta\" if((Test-Path -path $servicePath)) { <-- throws here. dowork } } So how can I pass my variables to the scriptblock $block? 回答1: Keith's answer also works for Invoke-Command , with the limit that you can't use named parameters. The arguments should be set using the -ArgumentList parameter and should be comma separated.