Powershell - 命令在界面中有效,但在脚本中无效

标签 powershell

对脚本编写相当陌生。 我有一个非常基本的脚本,它在 ISE 中运行良好,但是当我在一个文件中运行它时却没有。 脚本:

#
# WPM Convert to Ascii.ps1
# Process to remove accented characters from a text file as they cause issues when importing to U4BW via GL07
# SP Jan 2019
#
# Parameters
#
$usefile    =$dir+"\"+'SPTEMP.txt'
$outfile    =$dir+"\"+'SPOUT.txt'

#
# Convert characters
#
Get-Content $usefile -replace 'a', 'A' |Set-Content $outfile 

简单地将 1 个文件中的字符输出到另一个文件。 从 U4BW(Agresso) 命令调用是:-

powershell.exe -ExecutionPolicy Unrestricted -File "c:\scripts\WPM Convert to Ascii.ps1" -infile "[File name]" -dir "[Directory]"

我已经调试了所有发送的参数(infile 和 dir),它们都很好。尝试提前关闭文件 (outfile)。

我知道这可能是一个基本问题,但我就是看不出来。 任何帮助感激不尽! 史蒂夫

最佳答案

您需要对脚本进行以下更改。

在脚本的顶部声明它,以便在脚本中实际识别调用中的 -dir 参数:

param($dir)

此外,您的替换命令看起来不对,-Replace 不是 Get-Content 的有效参数。你可能是这个意思?

(Get-Content $usefile) -replace 'a', 'A' | Set-Content $outfile

最终脚本(有一些其他小的改进):

# WPM Convert to Ascii.ps1
# Process to remove accented characters from a text file as they cause issues when importing to U4BW via GL07
# SP Jan 2019

# Passed parameters
param (
    # The base directory path
    $dir
)

# Derived parameters
$usefile = Join-Path $dir "SPTEMP.txt"
$outfile = Join-Path $dir "SPOUT.txt"

# Replace characters
(Get-Content $usefile) -replace 'a', 'A' | Set-Content $outfile 

然后这样调用它:

powershell.exe -ExecutionPolicy Unrestricted -File "c:\scripts\WPM Convert to Ascii.ps1" -dir "[Directory]"

关于Powershell - 命令在界面中有效,但在脚本中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54308636/

相关文章:

azure - VSTS 扩展 : "Cannot process command because of one or more missing mandatory parameters: appdirectory webappname ResourceGroupName"

powershell - 如何在 Powershell 中使用 Invoke-WebRequest 重新创建工作的 CURL 命令

arrays - 使用Powershell从数组中的字符串中提取值

html - 输出带有自己的 <TR> ID 的合并 HTML

powershell - 如何在管理员模式下从 PowerShell 启动进程?

.net - 可以将 null 从 Powershell 传递到需要字符串的 .Net API 吗?

windows-7 - 如何说服 powershell(通过任务计划程序运行)找到我的网络驱动器?

powershell - 关于 ISE 与带有 SystemEvents 的控制台的问题

powershell - 使用 Powershell 和测试路径,我如何区分 "folder doesn' t 存在”和 "access denied"

c# - 术语 ' ' 未被识别为 cmdlet 的名称,