You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

改用-File参数调用PowerShell脚本后Get-ChildItem无法找到目录

Problem Root Causes
  • Quoting & Escape Character Mishandling: When passing a path ending with a backslash from Perl to PowerShell via -File, the trailing backslash escapes the closing double quote in the command line. This causes PowerShell to interpret the quote as part of the path (leading to extra quotes in the error) and strips the trailing backslash.
  • PowerShell -File Parameter Parsing: Unlike -Command, the -File argument treats input strings more literally but relies on proper shell quoting to preserve path components. Improper quoting from Perl leads to mangled path values.
Step-by-Step Solutions

1. Fix the Perl Command Line

Adjust how you construct the PowerShell call in Perl to preserve the path correctly:

Option A: Use Single Quotes for the Path Argument

Single quotes are not processed by Windows' cmd.exe (which Perl's system() uses by default) and are treated as literal by PowerShell, preserving trailing backslashes and avoiding quote escaping issues:

my $out_pth = 'C:\target\directory\';
my $ps_script = 'C:\path\to\your\script.ps1';
my $cmd = "powershell.exe -File \"$ps_script\" '$out_pth'";
system($cmd);

Option B: Escape Trailing Backslashes

If you must use double quotes, escape the trailing backslash in Perl to prevent it from escaping the closing quote:

my $out_pth = 'C:\target\directory\';
# Replace trailing single backslash with two to escape it
$out_pth =~ s/\\$/\\\\/;
my $ps_script = 'C:\path\to\your\script.ps1';
my $cmd = "powershell.exe -File \"$ps_script\" \"$out_pth\"";
system($cmd);

2. Explicitly Define Parameters in PowerShell

Avoid relying on $args; explicitly declare the path parameter to ensure proper string parsing:

param(
    [Parameter(Mandatory=$true)]
    [string]$out_pth
)

# Verify the received path (remove after debugging)
Write-Host "Received path: '$out_pth'"

# Your original Get-ChildItem logic
Get-ChildItem -Path $out_pth -Recurse | Where-Object {
    $_.LastWriteTime -ge (Get-Date).AddHours(-72)
}

3. Verify Parameter Parsing

Add the Write-Host line from the script above to confirm the path PowerShell receives matches what Perl intended. This helps rule out any remaining quoting issues.

Additional Checks
  • Ensure the path in Perl does not contain unescaped special characters (like spaces) that could break command line parsing.
  • Confirm that PowerShell is running in the same context (32/64-bit) as Perl if your path relies on system-specific directories (e.g., Program Files vs Program Files (x86)).

内容的提问来源于stack exchange,提问作者Michele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 14:10:26