so I'm trying to use this load of powershell from here: Getting the current hash key in a ForEach-Object loop in powershell

$myHash.keys | ForEach-Object {
    Write-Host $_["Entry 1"]
}

It's all working but I want to output the value as part of another string, i.e.:

$results.notvalid | ForEach-Object {
    write-warning 'Incorrect status code returned from $_["url"], 
                                                   code: $_["statuscode"]'
}

so I want the output to be:

Incorrect status code returned from www.xxxx.com, code: 404

but instead I get

Incorrect status code returned from $_["url"], code: $_["statuscode"]

what am I missing?


BTW, this works if I just do

$results.notvalid | ForEach-Object {
        write-warning $_["url"]
    }

I then get

www.xxxx.com

有帮助吗?

解决方案

I prefer using format strings over embedded expressions (i.e. $()). I find it more readable. Also, PowerShell creates properties on a hashtable for each key, so instead of indexing (i.e. $_['url']) you can $_.url.

$results.notvalid |
    ForEach-Object { 'Incorrect status code returned from {0}, code: {1}' 
                    -f $_.url,$_.statuscode } |
    Write-Warning

其他提示

You must put string in double quote instead of single quote if you want variables to be read. Also, in this spot you are not accessing directly a variable value, so you should use $() to be sure code to be evaluated in advance.

$results.notvalid | ForEach-Object {
    write-warning "Incorrect status code returned from $($_['url']), code: $($_['statuscode'])"
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top