Concatenating function result with string in powershell
function log-file {
param($message)
Add-Content -path $logfile -Value "$(Get-Date) $message"
}
function ping-server {
param($server)
$ping = New-Object System.Net.NetworkInformation.Ping
$ping.Send("$server")
}
log-file "Pinging server = " + (ping-server $server).status
How can I get the above to work with one line rather than doing this:
$pingable = (ping-server $server).status
log-file "Pinging server = $pingable"
Solution 1:
Try making this modification to the log-file function call
log-file $("Pinging server = " + (ping-server $server).status)
Solution 2:
There are many ways to concatenate/glue strings in PowerShell, but I prefer avoiding the plus sign, because its main role is addition and sometimes messes things up with strings.
I think more efficient and readable way is the following:
log-file $("Pinging server = $((ping-server $server).status)")
Just wrap your function in $() and place it inside the double quotes.
Read more;