Reputation: 141
I wish to invoke this Set-FixedVariable multiple times with different input but i only manage to execute it one time when I call DeclareFixedVariables why is that?
Function DeclareFixedVariables
{
try
{
Set-FixedVariable -name 'fixModelName'-value $ModelName -size 30
Set-FixedVariable -name 'fixMasterSetId' -value $ReturnMessage.MasterSetID -size 36
Set-FixedVariable -name 'fixModelversionId'-value $ModelversionID -size 36
Set-FixedVariable -name 'fixStartDateStr' -value $StartDateStr -size 23
Set-FixedVariable -name 'fixCreateDate' -value $CreateDateStr -size 23
Set-FixedVariable -name 'fixModelChangeDate' -value $ModelChangeDate -size 23
Set-FixedVariable -name 'fixModelOwner' -value $ModelProperties.UserId -size 6
Set-FixedVariable -name 'fixChangeId' -value $ModelProperties.ChangeId -size 10
Set-FixedVariable -name 'fixChangeUser' -value $ModelProperties.UserId -size 10
Set-FixedVariable -name 'fixAfBolag' -value $afBolag -size 2
Set-FixedVariable -name 'fixThBolag' -value $thBolag -size 2
}catch
{
Write-Log -Message "***Invoking Set-FixedVariable failed***" -Path $LogFile -Level Info
}
}
function Set-FixedVariable
{
param( [parameter(mandatory)][string]$name,
[parameter(mandatory)][string]$value,
[parameter(mandatory)][int]$size
)
$sb = [System.Text.Stringbuilder]::new( ' ' * $size )
[void]$sb.Insert(0, $value)
Set-Variable -Name $name -Value $sb.ToString().Substring(0, $size) -Scope Script -Force
return $value
}
Upvotes: 1
Views: 1543
Reputation: 13537
Right now, the only real issue I'm seeing is that all of your variables are set using Set-FixedVariable
with only one try/catch
block, meaning that PowerShell will process each one, line by line, and then stop when the first one fails.
It would be better to handle that with a forEach
loop, like this.
Function DeclareFixedVariables
{
$VariableSettings = @(
@{Name='fixModelName';Value=$ModelName;Size=30},
@{Name='fixMasterSetId';Value=$ReturnMessage.MasterSetID;Size=36},
@{Name='fixModelversionId';Value=$ModelversionID;Size=23}
)
forEach($variableSetting in $VariableSettings){
try{
Set-FixedVariable @variableSetting
}
catch{
Write-Log -Message "***Invoking Set-FixedVariable failed for $($VariableSetting.Name) with value $($VariableSetting.Value)***" -Path $LogFile -Level Info
}
}
}
From a code review standard this is probably easier to read (especially if you tweak the layout a bit) and this way the code will execute on each item even if one of them fails.
Next step: You might want to double-check your assumptions for what Set-FixedVariable
is meant to do. It is very puzzling, why would it be helpful to have an array with a number of spaces in it before the value?
Upvotes: 3