为什么此PowerShell脚本会产生错误?

时间:2017-01-01 11:39:38

标签: powershell

我在目录Eric Clapton - Nothing But The Blues - Full Concert (1994) [HQ].URL中有一个名为C:\Hans\Hans4\的文件。

创建此代码的代码如下(尽管无论文件内容如何都会发生错误)

$fileContents = @"
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
URL=http://example.com/
IDList=
"@

New-Item -Path "C:\Hans\Hans4" `
         -Name "Eric Clapton - Nothing But The Blues - Full Concert (1994) [HQ].URL" `
         -ItemType "file" `
         -Value $fileContents `
         -Force

当我运行以下内容时出现错误

Get-ChildItem 'C:\Hans' -Recurse | Resolve-ShortcutFile > Output.txt

代码引用下面的函数

function Resolve-ShortcutFile {         
    param(
        [Parameter(
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            Position = 0)]
        [Alias("FullName")]
        [string]$fileName
    )
    process {
        if ($fileName -like "*.url") {
            Get-Content $fileName | Where-Object {
                $_ -like "url=*"
            } |
            Select-Object @{
                Name='ShortcutFile'
                Expression = {Get-Item $fileName}
            }, @{
                Name='Url'
                Expression = {$_.Substring($_.IndexOf("=") + 1 )}
            } 
        }
    }
}

这是错误消息

Get-Content : An object at the specified path C:\Hans\Hans4\Eric Clapton - Nothing But 
The Blues - Full Concert (1994) [HQ].URL does not exist, or has been filtered by 
the -Include or -Exclude parameter.
At line:33 char:28
+             Get-Content $fileName | Where-Object {
+             ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (System.String[]:String[]) [Get-Content], Exception
    + FullyQualifiedErrorId : ItemNotFound,Microsoft.PowerShell.Commands.GetContentCommand

为什么我会收到此错误?

1 个答案:

答案 0 :(得分:15)

问题是传递给函数并传递给Get-Content

的文件名
  

C:\ Hans \ Hans4 \ Eric Clapton - Nothing But The Blues - Full Concert   (1994) [HQ] .URL

您遇到了here所描述的问题。

它包含方括号,解释为range operator with the set H and Q

因此该模式意味着它尝试使用以下任一名称来读取文件的内容......

  • Eric Clapton - Nothing But The Blues - Full Concert(1994) H .URL
  • Eric Clapton - Nothing But The Blues - Full Concert(1994) Q .URL

...但与

中的文字[HQ]不匹配
  • Eric Clapton - 蓝调 - 完整音乐会(1994) [HQ] .URL

您可以使用-literalPath参数来避免此问题,并按字面意思处理文件名。

function Resolve-ShortcutFile {         
    param(
        [Parameter(
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            Position = 0)]
        [Alias("FullName")]
        [string]$fileName
    )
    process {
        if ($fileName -like "*.url") {
            Get-Content  -literalPath $fileName | Where-Object {
                $_ -like "url=*"
            } |
            Select-Object @{
                Name='ShortcutFile'
                Expression = {Get-Item  -literalPath $fileName}
            }, @{
                Name='Url'
                Expression = {$_.Substring($_.IndexOf("=") + 1 )}
            } 
        }
    }
}