【问题标题】:My script run in ISE but got an error in console我的脚本在 ISE 中运行,但在控制台中出现错误
【发布时间】:2019-12-22 04:55:41
【问题描述】:

我的脚本在 ISE 中运行,但是当我想在 cmd 中运行它或右键单击我的脚本文件并使用 Powershell 运行时,我收到一条错误消息。
我在 Windows 7 上,我的 Powershell 版本是 Powershell 2.0

已经尝试执行

powershell.exe -STA -FILE "C:\Users\Mgtspare\Documents\Conversion\Conversion_Script.ps1"

我的脚本:

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Users\Mgtspare\Downloads"
$watcher.Filter = "*.xls"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$action = { 
            $watcher.Path *.xls | rename-item -newname { [io.path]::ChangeExtension($_.name, "xlsx") }
          }    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
Register-ObjectEvent $watcher "Created" -Action $action
while ($true) {sleep 5}

错误信息:

您必须在“*”运算符的右侧提供值表达式。

【问题讨论】:

  • $watcher.Path *.xls 无效。也许您只想将属性通过管道传递到命令 $watcher.Path | rename-item .....
  • 我找到了解决方案 $watcher.Path 是问题:)

标签: powershell windows-7 powershell-2.0


【解决方案1】:

$watcher.Path 是我脚本的问题,我更改了脚本,如果有人需要,您可以在下面看到解决方案:

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "C:\Users\Mgtspare\Downloads"
    #$watcher.Filter = "*.*"
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
    $action = { 
                Get-ChildItem -Path C:\Users\Mgtspare\Downloads *.xls | rename-item -newname { [io.path]::ChangeExtension($_.name, "xlsx") }
              }

### DECIDE WHICH EVENTS SHOULD BE WATCHED 
    Register-ObjectEvent $watcher 'Created' -SourceIdentifier 'FileCreated' -Action $action
    while ($true) {sleep 5}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多