首页 > 解决方案 > Powershell启动excel自动转义空格

问题描述

我编写了一个 Powershell 脚本 (GetMyTimesheet.ps1),它根据今天的日期计算出 excel 文件的名称和位置。最相关的行:

$sheetName = '"Project Timesheet - ' + $currentMonth + ' ' + (get-date).year + ' - Billy Bob.xlsm"'
start excel $sheetName

在我的计算机上,这可以按预期工作,并使用计算的文件名打开一个 excel 文件。但是,当在我同事的计算机上运行相同的 powershell 代码时,Excel 会返回一条错误消息:

Sorry, we couldn't find Project%20Timesheet%20-%20February%202019%20-%20Billy%20Bob.xlsm. Is it possible it was moved, renamed or deleted?

问题似乎是,当在他的计算机上运行 start excel $sheetName 命令时,$sheetName 中的每个空格都被转义/替换为 %20。为什么会发生这种情况?有什么办法让它不发生吗?

可能相关的是,这里的 .ps1 文件是由批处理文件 (deploy.bat) 生成的。我已经检查过了,生成的文件中包含的代码是相同的。它还由编译的 Autohotkey 可执行文件运行,Windows 10 最初会引发错误,因为它无法识别它/认为它可能是恶意的。这就是所做的一切:

if !FileExist("GetMyTimesheet.ps1")
    RunWait, deploy.bat

Run C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "GetMyTimesheet.ps1"

编辑:发布完整代码以供参考 - Powershell:

H:
cd Engineering
cd "# Timesheets"
cd (get-date).year
$test = Get-ChildItem | Where{$_.PSIsContainer} | Select Name
$month = $test| Sort-Object -Property Name | Select-Object -Last 1
cd $month.Name
#dir
#pause
$monthList = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
$currentMonth = $monthList[[int]$month.Name-1]
$sheetName = '"Project Timesheet - ' + $currentMonth + ' ' + (get-date).year + ' - Billy Bob.xlsm"'
start excel $sheetName

写入该 .ps1 的批处理文件:

echo off

set /p name="Enter your name exactly as it appears on the timesheet excel file: " 


(echo H:
echo cd Engineering
echo cd "# Timesheets"
echo cd ^(get-date^).year

echo $test = Get-ChildItem ^| Where{$_.PSIsContainer} ^| Select Name

echo $month = $test^| Sort-Object -Property Name ^| Select-Object -Last 1

echo cd $month.Name
echo #dir
echo #pause

echo $monthList = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
echo $currentMonth = $monthList[[int]$month.Name-1]

echo $sheetName = '"Project Timesheet - ' + $currentMonth + ' ' + (get-date).year + ' - %name%.xlsm"'

echo start excel $sheetName) > GetMyTimesheet.ps1

标签: powershell

解决方案


推荐阅读