Reputation: 37
First time user here but basically this is what I have been trying to figure out how to do for the past couple of days and I am now stuck.
$ImaginaryTestCase = @('Ted', 'Bill', 'Tom', 'Bob')
$ImaginaryTestCase -Contains 'Bill'
This should output as true, the issue I am having is that I need to take that True output, throw it into a file that says " Bill: True" in that text file. I know I can get the True Statement to come out and output easily to a file using Output-File but I would like to modify it before it goes to that point.
What do I need to do to make that happen?
Upvotes: 0
Views: 51
Reputation: 4694
You can try using the switch statement.
$ImaginaryTestCase = @('Ted', 'Bill', 'Tom', 'Bob')
switch -Exact ($ImaginaryTestCase){
"Bill" {"$_`: True" }
} #| Out-File -FilePath C:\Path\text.txt
Its a pretty handy tool and comparable to the ifstatement. Used like so:
Switch (<test-value>)
{
<condition> {<action>}
<condition> {<action>}
}
In your case, it iterates through the array, finds the condition you've set in matching the string "Bill". Then it executes an action based off that condition. In this case, its just passing back the Object using $_
that it used to match the string, and added the, ": True
" for what youre after.
Upvotes: 0
Reputation: 24071
Use an if statement to build a block of code that is executed when search is successful. Let's have an example like so,
$i = @('Ted', 'Bill', 'Tom', 'Bob')
$p = 'Bill'
if($i -contains $p) {
$result = "{0}:{1}" -f $p, "it is troo!"
write-host $result
}
# Output:
Bill:it is troo!
The $result
variable contains a string, which is built on .Net composite formatting. The {0}
and {1}
are placeholders in string, which will contain whatever comes after the formattig -f
switch.
Upvotes: 1