【问题标题】:Does Powershell have a cache that needs to be cleared?Powershell 是否有需要清除的缓存?
【发布时间】:2013-01-08 06:48:44
【问题描述】:

今天早上,我从本地网络驱动器复制了一个目录到临时文件夹进行测试。出现了这个错误。

Get-Content : Cannot find path 'C:\users\xxxxx\desktop\cgc\Automatic_Post-Call_Survey_-_BC,_CC.txt' because it does no
t exist.
At C:\users\xxxxx\desktop\cgc\testcountexcl1.ps1:55 char:12
+ Get-Content <<<<  $txtfile | Get-WordCount -Exclude (Get-Content c:\temp\exclude.txt) | select -First 15
    + CategoryInfo          : ObjectNotFound: (C:\users\xxxxx...ey_-_BC,_CC.txt:String) [Get-Content], ItemNotFoundEx
   ception
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

这是预期的移动...PS找不到引用的路径...但是我在运行脚本之前进行了以下更改(旧的在新的上方注释掉了):

$input = Get-Content c:\temp\wordCount.txt
<# $inpath = "C:\users\xxxxx\desktop\cgc\tx"    #>
$inpath = "C:\temp\tx"  
$srcfiles = Get-ChildItem $inpath -filter "*.txt"    
$notPermittedWords = Get-Content c:\temp\exclude.txt 

我的第一个想法是,有某种缓存保存了我上次运行时的 $inpath 变量……但无法确定这是否是预期的 PowerShell 行为。我是否误解了错误或解决方案?如何刷新缓存或任何可能存储在内存中的变量?

【问题讨论】:

  • 您确定整个代码都运行了两次吗?设置$inpath$srcfiles 的行都以新值第二次执行?
  • 它们是用新值执行的,但表现得好像它们被传递了旧值。

标签: caching powershell


【解决方案1】:

变量存储在会话中,因此如果您关闭您的 powershell 控制台并打开一个新控制台,所有自定义变量都将消失。如果您想查看存在哪些变量,请使用 Get-Variable 。要删除特定变量(以确保它消失),您可以使用:

Remove-Variable varname.

至于你的问题。全局(会话)范围内的变量存储在会话中,直到它被删除或覆盖。如果您使用相同的 powershell 控制台两次运行该代码,那么 $inpath 第二次应该设置为 "C:\temp\tx"$srcfiles 将使用新的文件列表进行更新。

【讨论】:

    【解决方案2】:

    我不喜欢每次需要清除缓存时都必须关闭并重新打开的想法。

    这适用于 PowerShell

    Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host

    【讨论】:

    • Remove-Module * 不太有用。否则应跟 Import-Module 后
    • 显然是我正在寻找的答案。我已将此行放在脚本的顶部,现在我不必每次都重新/打开 PS ISE。
    【解决方案3】:

    除了@Patrick's answer,您还可以像这样删除指定的模块:

    ,@("MyModule1","MyModule2") | %{&remove-module -erroraction:silentlycontinue $_}
    

    管道方式灵感来自here

    所以帕特里克的单行将变成Remove-Variable * -ErrorAction SilentlyContinue; ,@("MyModule1","MyModule2") | %{&amp;Remove-Module -ErrorAction:SilentlyContinue $_}; $error.Clear(); Clear-Host

    【讨论】:

      猜你喜欢
      • 2013-04-13
      • 2014-07-04
      • 2017-08-18
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多