0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

powershell 気になったこと

Last updated at Posted at 2022-07-31

環境

  • windows 10
  • PowerShell 7.x

valuefrompipelinebypropertyname

System.Management.Automation.ArgumentTypeConverterAttributeでキャスト可能であれば、引数の型に変更してくれる

enum keyCodes {
    vk_A = 0x41
    ...
    ...
}
function func {
    [CmdletBinding()]
    param (
        [Parameter(Position=0, Mandatory, ValueFromPipeline, ValueFromPipelinebyPropertyName)]
        [ValidateNotNullOrEmpty()]
        [int] $code1,

        [Parameter(Position=1, Mandatory, ValueFromPipeline, ValueFromPipelinebyPropertyName)]
        [ValidateNotNullOrEmpty()]
        [string] $code2
    )

    process {
        Write-Output "$code1, $code2"
    }
}

[keyCodes]::vk_A | func
実行結果
65, vk_A

Call演算子

Write-Output後の一回目の値が変わらない
dot演算子、foreach-Objectでは期待通りに動作する

$dateAfterWriteOutput = Get-Date
$dateBeforeWriteOutput = Get-Date
while ($true) {
    1..3 | & {
        process {
            $dateBeforeWriteOutput = Get-Date
            Write-Output "$_ > After : $dateAfterWriteOutput, Before : $dateBeforeWriteOutput"
            Start-Sleep -s 1
            $dateAfterWriteOutput = Get-Date
        }
    }
}
実行結果
1 > After : 07/31/2022 18:21:31, Before : 07/31/2022 18:21:31
2 > After : 07/31/2022 18:21:32, Before : 07/31/2022 18:21:32
3 > After : 07/31/2022 18:21:33, Before : 07/31/2022 18:21:33
1 > After : 07/31/2022 18:21:31, Before : 07/31/2022 18:21:34
2 > After : 07/31/2022 18:21:35, Before : 07/31/2022 18:21:35
3 > After : 07/31/2022 18:21:36, Before : 07/31/2022 18:21:36
1 > After : 07/31/2022 18:21:31, Before : 07/31/2022 18:21:37
2 > After : 07/31/2022 18:21:38, Before : 07/31/2022 18:21:38
3 > After : 07/31/2022 18:21:39, Before : 07/31/2022 18:21:39

beginブロックに書けば期待通りに動作する

while ($true) {
    1..3 | & {
        begin {
            $dateAfterWriteOutput = Get-Date
            $dateBeforeWriteOutput = Get-Date
        }
        process {
            $dateBeforeWriteOutput = Get-Date
            Write-Output "$_ > After : $dateAfterWriteOutput, Before : $dateBeforeWriteOutput"
            Start-Sleep -s 1
            $dateAfterWriteOutput = Get-Date
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?