【问题标题】:How to concat path and file name for creation and removal如何连接路径和文件名以进行创建和删除
【发布时间】:2014-06-27 16:15:24
【问题描述】:

我正在尝试以下方法。

$woohoo = "c:\temp\shabang"
New-Item -ItemType File $woohoo

这会在所需位置创建一个文件。但是,我想将$woo$hoo 分开,然后做这样的事情。

$woo = "c:\temp"
$hoo = "shabang"
New-Item -ItemType File ($woo + $hoo)

这不起作用,我需要一个关于如何让它飞起来的提示。 This suggestionthis on 适用于我的情况时都解决了。显然 - 不支持给定的路径格式。

建议?

编辑

这是它的样子:

编辑 2

$woo = "c:\temp"; $hoo="沙邦"; New-Item -ItemType 文件 (Join-Path $woo $hoo)

【问题讨论】:

    标签: string powershell concatenation filepath


    【解决方案1】:

    执行$woo + $hoo 不会返回正确的文件路径:

    PS > $woo = "c:\temp"
    PS > $hoo = "shabang"
    PS > $woo + $hoo
    c:\tempshabang
    PS >
    

    相反,您应该使用Join-Path cmdlet 来连接$woo$hoo

    New-Item -ItemType File (Join-Path $woo $hoo)
    

    请看下面的演示:

    PS > $woo = "c:\temp"
    PS > $hoo = "shabang"
    PS > Join-Path $woo $hoo
    c:\temp\shabang
    PS >
    

    【讨论】:

    • 似乎还有其他问题。我运行了确切的行(新项目...)并得到“路径上不支持的格式”。请查看编辑,看看我没有说谎。 :)
    • 您需要复制并粘贴您正在运行的确切代码和确切的错误消息。
    • @Bill_Stewart 复制到哪里?这里?请查看编辑(15 秒后)。
    • @Bill_Stewart HA!发现问题了!目录需要完整地存在。 然后它起作用了!那里没有非法行为 - 只是没有创建目录。
    【解决方案2】:
    $path=Get-Location 
    $file="myfile.json"
    $path=Join-Path $path $file
    
    #you can cast to a class if the class definition is known
    $results = (Get-Content -Path $path  | Out-String | ConvertFrom-Json)
    
    foreach($tempObj in $results)
    {
       $obj_vals=$tempObj|Select-Object -Property *
       Write-Host $obj_vals  -ForegroundColor Green
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 2016-01-11
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 2011-03-22
      • 2015-12-30
      • 2019-12-01
      相关资源
      最近更新 更多