【问题标题】:PowerShell update variable while script is running脚本运行时 PowerShell 更新变量
【发布时间】:2020-12-09 00:29:11
【问题描述】:

如何在脚本运行状态下更新 PowerShell 中的变量?

我遇到这样的情况,脚本会持续监控磁盘的大小,并将其与共享驱动器上的文本文件中的数字(比如 Z:\quota\software-share-size.txt)进行比较。如果文本文件中的数字大于它监视的磁盘大小,则它会发送一封电子邮件以将磁盘扩展到文本文件中提到的新大小。但是一旦脚本启动,它就不会从文件中提取新号码,我不想停止并启动脚本以从文本文件中加载新内容。请帮忙

【问题讨论】:

  • 你通过赋值来更新变量的值,即。 $variable = <# some expression here #>。请向我们展示您需要帮助的脚本

标签: windows powershell scripting


【解决方案1】:

也许这可以帮助你:

while($true)
{
#Here i pull my disk (C:) infomations (i use localhost for my computer, but you can use an IP or a file with multiple IP)

$diskinfo = Get-WmiObject Win32_LogicalDisk -ComputerName localhost | where {$_.DeviceId -eq 'C:'} 

#Here you pull only the freespace value with Gb format (default is byte)
$freespace = $diskinfo.freespace/1Gb
$freespace = [int]$freespace

#here you pull the "limit number" off your file, must be in Gb and only the number is written in the file.
$limit=Get-Content -Path "B:\Dev\filewithsizeingo.txt"
$limit = [int]$limit


if ($freespace -gt $limit) #The free diskspace is greater than the limit
{
    Write-Host "Diskfreespace is Above Limit" -f Green
}
elseif ($freespace -lt $limit) #The free diskspace is inferior than the limit 
{
    Write-Host "Free diskspace below limit" -f Red
    #break
    #code mail sending
}
Start-Sleep 1
}

因为是循环,所以可以在不停止脚本的情况下修改filewithsizeingo.txt,每次循环时脚本都会刷新空闲磁盘空间和限制值。

在 elseif 语句中,您可以插入中断并编码发送电子邮件(我还不知道),不要忘记中断,否则它将每秒发送一封邮件。

我希望它对你有所帮助,或者至少它给了你新鲜的想法(我是一个 powershell 的初学者,代码可以改进)。

【讨论】:

    猜你喜欢
    • 2014-08-01
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    相关资源
    最近更新 更多