【问题标题】:Retrieve Values from text file and use them as Variable in PowerShell从文本文件中检索值并将它们用作 PowerShell 中的变量
【发布时间】:2020-11-27 12:19:00
【问题描述】:

请不要杀我,因为我是 Windows 系统管理的新手 ;) 几个月前开始的,所以我需要一些帮助:

基本上,我想使用从文本文件发出的值作为变量: ($Clustername 和 $NewFSWPath)如下面的 PS 代码所述:

$ClusterName = "GLA-CLU"
$NewFSWPath = "\\DC01\SQL-CLU"


#As quorum file share witness is a cluster core resource, the only way to remove an existing FSW in PS is to switch the cluster to node majority. It will remove the existing Cluster File Share Witness from the chosen cluster
Set-ClusterQuorum -Cluster $ClusterName -NodeMajority
#Set New Quorum File Share Witness for the cluster
#Add-ADGroupMember $FileShareSecurityGroup -Members "$ClusterName"
$t = $host.ui.RawUI.ForegroundColor
$host.ui.RawUI.ForegroundColor = "Yellow"
Write-Output "Setting A New Location for File Share Witness on cluster: '$($ClusterName)':"
Write-Host "`r"
$host.ui.RawUI.ForegroundColor = $t
Set-ClusterQuorum -Cluster $ClusterName -NodeAndFileShareMajority $NewFSWPath
Write-Host "`r"
$host.ui.RawUI.ForegroundColor = $t
$host.ui.RawUI.ForegroundColor = "Yellow"
Write-Output "Checking New File Share Witness Availablity:"
$host.ui.RawUI.ForegroundColor = $t
Get-clusterresource -cluster $ClusterName | where-object {$_.ResourceType -like "File Share Witness"} | get-clusterparameter

非常感谢。 谢谢。

【问题讨论】:

  • 这里的问题到底是什么?如何从文本文件中提取值?在这种情况下,请显示文件并告诉我们要提取的值是什么。
  • 嗨,谢谢。我需要替换变量的值(请参阅我复制的脚本): $ClusterName = "GLA-CLU" >> 相反,必须从现有文本文件 $NewFSWPath = "\\DC01\SQL 存储和检索此值-CLU" >> 相同,但此值必须存储在文本文件中,例如 TEXT FILE 将是:Clustername=GLA-CLU NewFSWPath=\\DC01\SQL-CLU

标签: powershell powershell-2.0 powershell-3.0 sysadmin


【解决方案1】:

假设您的 TEXT_FILE.TXT 仅包含两行:

Clustername = GLA-CLU
NewFSWPath = \\DC01\SQL-CLU

然后

$Path = "C:\TEXT_FILE.TXT"
$Lines = [System.IO.File]::ReadLines($Path)
$Token = $Lines.Split('=').Trim()
$ClusterName = $Token[1]
$NewFSWPath = $Token[3]

Write-Host $ClusterName
write-host $NewFSWPath

输出:

GLA-CLU
\\DC01\SQL-CLU

现在您可以根据需要在脚本中使用变量$ClusterName$NewFSWPath

【讨论】:

  • 谢谢。我设法修复它,使用:Get-Content 'fswsiteconf.txt' | Foreach-Object{ $var = $_.Split('=') New-Variable -Name $var[0] -Value $var[1] } 它以这种方式工作。你觉得呢?
  • 如果它有效并满足您的要求,那么就是这样,您应该使用它。您的问题在这里有解决方案 --> stackoverflow.com/questions/12368142/…
【解决方案2】:

谢谢,但我设法解决了:

Get-Content 'fswsiteconf.txt' | Foreach-Object{
$var = $_.Split('=')
New-Variable -Name $var[0] -Value $var[1] }

现在使用上面指出的代码对我有用 您认为解决方案是什么?

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2014-04-23
    • 2015-04-09
    • 2016-01-04
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多