J'ai travaillé sur un code PowerShell et en essayant de le rendre aussi lisible que possible (quelque chose PS est très agréable à). Bien que nous ayons une fonction Add-Member et une fonction Get-Member, il n'y a pas de fonction Set-Member associée. Donc, je suis allé environ en créer un pour mon projet. Cependant, dans la fonction elle-même (comme indiqué ci-dessous), il me exige d'utiliser la ligne:
$_.$NotePropertyName = $NotePropertyValue
à travailler, mais je pense que je devrais utiliser la ligne mais il ne fonctionne pas:
$InputObject.$NotePropertyName = $NotePropertyValue
Quelqu'un peut-il m'aider à comprendre pourquoi il réagit de cette façon? Merci!
Function Set-Member
{
[CmdletBinding(DefaultParameterSetName='Message')]
param(
[Parameter(ParameterSetName='Message', Position=0, ValueFromPipeline=$true)] [object[]]$InputObject,
[Parameter(ParameterSetName='Message', Mandatory=$true)] [string]$NotePropertyName,
[Parameter(ParameterSetName='Message', Mandatory=$true)] [string]$NotePropertyValue
)
$strInitialValue = $InputObject.($NotePropertyName) #Get the value of the property FirstName for the current object in the pipe
$_.$NotePropertyName = $NotePropertyValue
}
$objTest = [PSCustomObject]@{
FirstName = "Bob"
LastName = "White"
}
$objTest | ForEach-Object {
$_ | Set-Member -NotePropertyName "FirstName" -NotePropertyValue "Joe"
$_ #Push the object back out the pipe
}
$objTest | ForEach-Object {
$_ | Set-Member -NotePropertyName "FirstName" -NotePropertyValue "Bobby$($_.FirstName)"
$_ #Push the object back out the pipe
}
Je suis désolé. mais je ne comprends vraiment pas quel est le but de cette fonction –
Hey CB .... C'est vraiment juste pour ceux qui lisent mon code en interne voir le verbiage "Set-Member" pour le rendre très clair ce qu'il fait. Mon code actuel fait juste le changement de ligne et a du sens pour moi, mais je pensais que pour l'avenir, il serait bien d'avoir une cmdlet nommée. –