New-Item即使在' if'内执行也是如此。声明

时间:2017-03-30 13:45:37

标签: powershell

我创建了一个脚本来从2个IP摄像头中提取JPEG快照。为了让我保持井井有条,我添加了一些行来检查日期并创建一个匹配它的文件夹。该脚本还会检查文件夹是否存在,如果存在,则应跳过快照捕获。

一切都按预期工作正常但似乎由于某种原因,脚本仍然试图在我的PS控制台中创建文件夹并显示和错误该目录存在。

$chk_path = Test-Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$Camera_A = (new-object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_A$((Get-Date).ToString('HH-mm-ss')).jpeg")
$Camera_B = (new-object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))\Camera_B$((Get-Date).ToString('HH-mm-ss')).jpeg")
if (-not ($chk_path) ) {
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder
} else {
write-host "C:\SnapShots exists, Saving SnapShots"
}
Camera_A
Camera_B

3 个答案:

答案 0 :(得分:0)

以下代码段应该有效:

$str_path = "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"
$chk_path = Test-Path $str_path
if ($chk_path) {
    $Make_SnapShot_Folder = Get-Item -Path $str_path
} else {
    $Make_SnapShot_Folder = New-Item -ItemType Directory -Path $str_path
}
$Make_SnapShot_Folder      ### this outputs a DirectoryInfo

答案 1 :(得分:0)

移动此行:

$Make_SnapShot_Folder = 
    New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"

到这里:

if (-not ($chk_path) ) {
<-- Here
write-host "C:\SnapShots doesn't exist, creating it"
$Make_ScrapShot_Folder <-- Remove this line

答案 2 :(得分:0)

与您可能使用的其他语言不同,PowerShell会在分配给变量时执行代码,而不是在变量调用时。

所以你实际上是用这一行创建文件夹:

$Make_SnapShot_Folder = New-Item -ItemType Directory -Path "C:\SnapShots\$((Get-Date).ToString('yyyy-MM-dd'))"

您可以重新安排代码,使其达到您想要的效果,并提高效率:

$day = Get-Date -Format 'yyyy-MM-dd'
$snapshots_dir = "C:\SnapShots\$day"

if (Test-Path $snapshots_dir) {
    Write-Host "$snapshots_dir exists, Saving SnapShots"
} else {
    Write-Host "$snapshots_dir doesn't exist, creating it"
    New-Item -ItemType Directory -Path $snapshots_dir
}

$timestamp = Get-Date -Format 'HH-mm-ss'

(New-Object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"$snapshots_dir\Camera_A$timestamp.jpeg")
(New-Object System.Net.WebClient).DownloadFile('http://10.0.0.132/snap.jpeg',"$snapshots_dir\Camera_B$timestamp.jpeg")