I want to create a function that take a array of pc and check if a pc name in parameter match with a pc name in the array at index of $i but when i create this function my function has a bug, the bug is $nomPeripherique is empty but i call it with "DESKTOP-QVRFEN4"
$tableauPeripherique= @("DESKTOP-QVRFEN4","DESKTOP-QVRETTD")
function Redemarrer($tableauPeripherique,$nomPeripherique){
for ($i = 0; $i -lt $tableauPeripherique.Length; $i++)
{
if ($tableauPeripherique[$i] -eq $nomPeripherique)
{
Restart-Computer -ComputerName $nomPeripherique
}
else
{
echo "nom de peripherique n'est pas présent dans la liste"
}
}
}
Redemarrer($tableauPeripherique,"DESKTOP-QVRFEN4")
Your are calling the function incorrectly. This is a common mistake for New PowerShell users as in many programming languages the function call has the arguments parenthetically stated after the Function name.
The call should look like:
Redemarrer $tableauPeripherique "DESKTOP-QVRFEN4"
No comma & no parens. The way you are calling it you're passing an entire array as the first argument. As such there's no second argument to compare to within the loop.
Personally I prefer advanced parameters. While there's a lot to know on the topic of Advanced Functions and their parameters there's still a low barrier to entry.
function Redemarrer
{
Param(
[Parameter(Mandatory = $true, Position = 0)]
[String[]]$tableauPeripherique,
[Parameter(Mandatory = $true, Position = 1)]
[String]$nomPeripherique
) # End Param block...
Process{
for ($i = 0; $i -lt $tableauPeripherique.Length; $i++)
{
if ($tableauPeripherique[$i] -eq $nomPeripherique) {
Restart-Computer -ComputerName $nomPeripherique
}
else {
Write-Output "nom de peripherique n'est pas présent dans la liste"
}
}
} # End Process Block...
}
Note: You do not need Write-Output
or it's alias echo
. More importantly the function will return the string if & when the else block fires. This can be problematic if you are assigning the function return and/or piping to another command. In short if your only intent is to write something to the console use Write-Host
instead. However, as you get more advanced there are reasons not to do that either.
Of course this answer is a poor substitute for the topic. One good relatively entry level book on the matter is "Learn PowerShell Scripting in a Month of Lunches" by Don Jones & Jeffrey Hicks. Incidentally Don Jones has a lot to say about Write-Host
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.