【问题标题】:Powershell here-string expansionPowershell here-string 扩展
【发布时间】:2014-09-25 18:46:23
【问题描述】:

这里的字符串

有一些关于 Powershell 'here-string' 的示例,但我几乎没有遇到过 'here-string' 扩展。所以我发布这个是为了提供一些帮助。

当你想添加一些带有换行符的文字时,单引号和双引号都不需要转义,也不需要像"`r`n" 这样的换行符。 'here-strings' 在 PowerShell 中发挥了作用。 他们应该以

开头

@"
和换行符,应该以换行符结束
"@

For example:                        |Result:
                                    |
@"                                  |
Hello world! 09/25/2014 11:39:56    |      Hello world! 09/25/2014 11:39:56
'(this will appear as is)'          |      '(this will appear as is)'
!                                   |      !
"@                                  |

【问题讨论】:

  • 我会删除你的第一个例子,因为它有点误导 - 结束 "@ 必须出现在第 0 列的新行上。这里的字符串也可以是单引号和双引号。双引号字符串不仅支持变量插值,还支持子表达式,例如$((get-process -id $pid).MainWindowTitle).
  • @Keith 我已经编辑了第一个示例。我正在寻找特定于变量插值的“here-string”示例,并且在谷歌搜索后没有遇到任何问题。所以我只是发布了具体的解决方案。我认为 'here-string' 的其他应用示例很多而且很容易找到。
  • 在使用 Google 之前,请尝试查看 PowerShell 帮助。 :-) 特别是man about_Quoting_Rules
  • 现在我回过头来尝试 man &%^%^%&^ 但我仍然要谷歌 man &^%*^&*^ 首先找到我要配员

标签: powershell powershell-3.0


【解决方案1】:

下面是如何引入 CmdLet 和一个日期变量来显示当前日期,如下所示:
例如以下是我们想要实现的:

Hello world! 09/25/2014 11:39:56
'(this will appear as is)'
!

方法如下:

@"
Hello world! $(Get-Date)
'(this will appear as is)'
!
"@

或带变量:

$myDate = Get-Date
@"
Hello world! ${myDate}
'(this will appear as is)'
!
"@

【讨论】:

  • 很高兴知道这一点。我修复了您的此处字符串终止,因为它们不正确 @" 文本 "@。它正在等待编辑。否则你会得到这个错误The string is missing the terminator: "@
【解决方案2】:

这篇文章很有帮助,我是通过在 SQL 查询中寻找扩展 PowerShell here-string 中的变量而来到这里的。

以下代码片段将获取服务器列表,然后循环输入Foreach-Object,允许为每个查询替换服务器名称!

感谢@Matt 提供hash-table help

$servers = Get-Content c:\scripts\list.txt

$servers | ForEach-Object{
 $items = @{}
 $items.Server = $_

$query = @"
 WHERE svrName = $($items.Server)
"@
}

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2021-11-01
    • 2017-04-09
    • 1970-01-01
    相关资源
    最近更新 更多