我在 powershell 脚本中做错了什么

我在 powershell 脚本中做错了什么

好的,事情是这样的。我尝试编写一个 PowerShell 脚本来创建一些文件夹并更改 .txt 文件中的几个字符串。

但正如你所猜测的,它不起作用。请参阅下面的配置:

Start-Transcript
[string]$CustomerName = Read-host "Enter the company name of the customer (e.g. Companyname)"
write-host ""
[string]$Hostname = Read-host "Enter the FQDN of the customers machine (e.g. HV00.domain.local)"
write-host ""
[string]$Logon = Read-host "Enter te logon credentials of the customers machine (e.g. domain\user)"
write-host ""
[string]$Password = Read-host "Enter the password of the customers machine"
write-host ""

cd C:\Monitor\Logs
mkdir .\$CustomerName
cd C:\Monitor\Logs\$CustomerName
mkdir .\$Hostname
cd $Home

cd C:\Monitor\Scripts\CustomScript
mkdir .\$CustomerName
cd $Home

$InputFile = "C:\Monitor\Scripts\BaseScript\BaseScript.txt"
$OutputFile = "C:\Monitor\Scripts\CustomScript\$CustomerName\$CustomerName.txt"

这不起作用

(Get-Content $InputFile) | ForEach-Object { $_ 
-replace "hostname", "$Hostname" `
-replace "username@domainname", "$Logon" `
-replace "password", "$Password" } `
-replace "C:\Monitor\Logs\customername\hostname\", "C:\Monitor\Logs\$Customername\$Hostname\" 
} | Set-Content $OutputFile

这是有效的,但我只能用它替换一个字符串

(Get-Content $InputFile) -replace "hostname", "$Hostname" > $OutputFile

有人知道吗?

答案1

如果您能粘贴您遇到的错误,那就太方便了。但是您的 for 循环代码中有一个过多的右花括号,这可能是:

-replace "password", "$Password" } `  <=== this one

顺便说一句,你可以通过一次创建整个树来缩短子文件夹创建代码的数量,PowerShell 可以完美处理

mkdir c:\foo\bar\this\will\all\be\created\in\one\statement

相关内容