如何使这个foreach-object正确运行?

时间:2015-05-23 01:17:19

标签: powershell pipeline

我正在尝试使用列CompanyName,UserCount读取.csv并编辑.rdp文件。输出应创建多个.rdp文件,同时更改.rdp本身中的3行和名称。

到目前为止,我有这个:

$testRDP = (Get-Content C:\Users\Administrator.PT\Desktop\Test.rdp)
$remoteAPP = @()
$rdpName = @()
$companyNames=Import-Csv C:\Users\Administrator.PT\Desktop\CompanyNames.csv
foreach ($name in $companyNames) {
    for ($i = 1; $i -le $name.UserCount; $i++) {
        $remoteAPP = "RemoteApp" + $name.CompanyName + ".address.com"
        $rdpName = $name.CompanyName + $i + ".rdp"
        $aliasRDP = $name.CompanyName + $i
        ForEach-Object {$testRDP -replace 'remoteapp.address.com', $remoteAPP}
        ForEach-Object {$testRDP -replace 'user', $aliasRDP} | 
Out-File C:\Users\Administrator.PT\Desktop\$rdpName
        }
}

运行此选项会将'user'替换为$aliasRDP,但'remoteapp.address.com'保持不变。 我猜我的管道是错的。如果我能更好地澄清一些事情,请告诉我。

谢谢。

1 个答案:

答案 0 :(得分:3)

事实上,您根本不需要ForEach-Object

$testRDP = (Get-Content C:\Users\Administrator.PT\Desktop\Test.rdp)
$remoteAPP = @()
$rdpName = @()
$companyNames=Import-Csv C:\Users\Administrator.PT\Desktop\CompanyNames.csv
foreach ($name in $companyNames) {
    for ($i = 1; $i -le $name.UserCount; $i++) {
        $remoteAPP = "RemoteApp" + $name.CompanyName + ".address.com"
        $rdpName = $name.CompanyName + $i + ".rdp"
        $aliasRDP = $name.CompanyName + $i
        $testRDP -replace 'remoteapp.address.com', $remoteAPP -replace 'user', $aliasRDP | 
Out-File C:\Users\Administrator.PT\Desktop\$rdpName
        }
}

这是使用正则表达式匹配和替换字符串的版本。它更安全,因为原始脚本将替换文件中任何位置的匹配,这可能是致命的。

$testRDP = (Get-Content -Path 'C:\Users\Administrator.PT\Desktop\Test.rdp')
$companyNames = Import-Csv -Path 'C:\Users\Administrator.PT\Desktop\CompanyNames.csv'
foreach ($name in $companyNames) {
    for ($i = 1; $i -le $name.UserCount; $i++) {
            $remoteAPP = 'RemoteApp' + $name.CompanyName + '.address.com'
            $rdpName = $name.CompanyName + $i + '.rdp'
            $aliasRDP = $name.CompanyName + $i
            $testRDP -replace '^(full address:s:).*$', "`$1$remoteAPP" -replace '^(username:s:).*$', "`$1$aliasRDP" |
                Out-File -FilePath "C:\Users\Administrator.PT\Desktop\$rdpName"
    }
}