【问题标题】:$Env variable not recognized inside an if block$Env 变量在 if 块内无法识别
【发布时间】:2018-10-13 02:36:39
【问题描述】:

我正在尝试执行此代码,如果它比网络上的文件旧,它基本上只是通过网络将文件复制到本地登录用户的桌面。以下代码的第一行运行良好,但在 if 块中使用 $env:userprofile 的部分会引发错误。不知道这里发生了什么。

Copy-Item -Path "\\path1\subpath1\subpath2\Patch\help\*" -Filter *.chm -Destination "$Env:UserProfile\Desktop" -force -Recurse

$chmfileNetwork = Get-ItemPropertyvalue -Path 'path1\subpath1\subpath2\Patch\help\*' -Filter *.chm -Name 'LastWriteTime'

$chmfileLocal = Get-ItemPropertyValue -Path '$Env:UserProfile\Desktop\*' -Filter *.chm -Name 'LastWriteTime'

if ($chmfileLocal -lt $chmfileNetwork) {
    Copy-Item -Path "path1\subpath1\subpath2\Patch\help\*" -Destination "$Env:UserProfile\Desktop" -force -Recurse
} else {
    echo "Saul good, man"
}

这会引发错误

Get-ItemPropertyValue:找不到驱动器。名为“$Env”的驱动器 不存在。 在 C:\Users\user1\Downloads\PS2EXE-GUI\psfile.ps1:28 char:17 + ... fileLocal = Get-ItemPropertyValue -Path '$Env:UserProfile\Desktop\*' ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~ + CategoryInfo : ObjectNotFound: ($Env:String) [Get-ItemPropertyValue], DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetItemPropertyValueCommand

【问题讨论】:

  • 改用$home\Desktop
  • 感谢 TheMadTechnician,现在将尝试并告诉您是否可行。
  • 嘿,这行得通。非常感谢。您可以将其添加为答案吗?
  • '$Env:UserProfile\Desktop\*' -> "$Env:UserProfile\Desktop\*"

标签: powershell


【解决方案1】:

您可以使用$home\Desktop 获取用户的桌面文件夹,但 Ansgar Wiechers 确实指出了您的脚本的问题,即为什么它会抛出错误。您在 chmfileLocal = 行上使用了单引号。使用单引号时不会扩展变量,仅在使用双引号时才会扩展。原始脚本可以通过以下更改来修复:

$chmfileLocal = Get-ItemPropertyValue -Path "$Env:UserProfile\Desktop\*" -Filter *.chm -Name 'LastWriteTime'

【讨论】:

  • 非常感谢 TheMadTechnician 和 Ansgar Wiechars 的回答。
猜你喜欢
  • 2021-09-21
  • 1970-01-01
  • 2015-10-27
  • 2022-01-22
  • 2012-05-09
  • 2019-02-27
  • 1970-01-01
  • 2013-08-02
  • 2014-08-09
相关资源
最近更新 更多