改用-File参数调用PowerShell脚本后Get-ChildItem无法找到目录
- 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
-FileParameter Parsing: Unlike-Command, the-Fileargument treats input strings more literally but relies on proper shell quoting to preserve path components. Improper quoting from Perl leads to mangled path values.
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.
- 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 FilesvsProgram Files (x86)).
内容的提问来源于stack exchange,提问作者Michele

