【问题标题】:How to expand two properties from a single select-object and pass it onto Test-Path?如何从单个选择对象扩展两个属性并将其传递到测试路径?
【发布时间】:2021-05-07 12:09:42
【问题描述】:

我在寻找一种方法来扩展我需要传递到测试路径的选择对象中的两个属性时遇到问题。问题是如果我不扩展属性并传递到 Test-Path 我将在错误中得到 @{} - 我认为 powershell 将其视为对象?

有谁知道有没有办法做到这一点?

我尝试了一些类似下面的方法,但无济于事......

Invoke-Sqlcmd -ServerInstance $Database -Query $myquery | 
Where-Object {$_.Name -like "*JD*"} | Select @{Expression={$_.Name, $_.FileExtension -join "."}} | FT -HideTableHeaders

理想情况下,我的查询应该返回:

文件名.extension

然后我可以传递到 Test-Path 而无需 powershell 将其视为一个对象,如果我没记错的话是一个字符串?

编辑 1:不确定它是否有帮助,但我想我会在这里添加它,希望能更清楚。

我的 SQL 表有这样的数据:

Column A | Column B
FileName | FileExtension 

编辑 2:包括用于澄清和管道输出的 foreach 循环

$FilePath = "\\Server1\Folder1\Folder2\"
foreach ($path in $myquery) {


$path2 = $FilePath + $path


# check FileExtensions if exist or not 

    if (!(Test-Path $path2)) 
    {
    Write-host " $path  | Does not exist"
    }
    
}

管道输出如下所示:

\\Server1\Folder1\Folder2\@{LiteralPath=FileName.ExtensionName}
# This is getting treated as does not exist because I have "@{LiteralPath=}" left in there, if I can remove it I should be golden 

【问题讨论】:

  • 你能告诉我们Invoke-Sqlcmd -ServerInstance $Database -Query $myquery |Get-Member的输出吗?
  • Name 属性字符串 Name {get;set;} 和 FileExtension 属性字符串 FileExtension {get;set;}

标签: powershell


【解决方案1】:

如果我正确理解了这个问题,您希望在结果查询中合并两列中的文件名,然后测试该文件是否存在。

在那种情况下试试

Invoke-Sqlcmd -ServerInstance $Database -Query $myquery | 
    Where-Object {$_.Name -like "*JD*"} | 
    ForEach-Object {
        # it is unclear what the column names really are..
        # your example shows 'Column A' and 'Column A', but your code uses 'Name' or 'FileName'
        # and 'FileExtension', so you have to decide which is which..
        $file = '{0}.{1}' -f $_.'Column A', $_.'Column B'.TrimStart(".")
        # hopefully your query results in a complete path and filename, if not,
        # provide the path to the file here:
        # $file = Join-Path -Path $FolderPathWhereTheFileShouldBeFound -ChildPath $file

        # now you can test if the file exists
        if (Test-Path -Path $file -PathType Leaf) {
            # do something here
            Write-Host "File '$file' exists" -ForegroundColor Green
        }
        else {
            # bummer.. file not found
            Write-Host "File '$file' does NOT exist" -ForegroundColor Red
        }
    }

请阅读内联 cmets,因为我仍然不清楚太多..

【讨论】:

  • 做到了,非常感谢!还有一件事,如果您不介意,您能告诉我“{0}.{1}”是做什么的吗?
  • @JohnDoe '{0}.{1}' 是一个模板字符串,其中的占位符 {0}{1} 被替换为 -f 之后的值。 -f Format Operator 有很多选项可以让组合字符串变得轻而易举。看看那里!
猜你喜欢
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多