【问题标题】:How can I get a output from a powershell function into a output file for example txt?如何将 powershell 函数的输出转换为输出文件,例如 txt?
【发布时间】:2016-11-18 19:37:17
【问题描述】:

我在windows powershell中做了一个create函数:

function create(){
param(
$searchBase = "OU=Customers,DC=test,DC=nl",
$NewOUs = @(Import-csv -Path $txt_csv.Text -Delimiter ";"),
[switch]$ProtectOU
)

$Protect = $true
If ($ProtectOU){$Protect = $true}

<# ------- CREATE OU ------- #>
foreach ($NewOU in $NewOUs) {
    try {
        New-ADOrganizationalUnit -Name $NewOU.company -Description $NewOU.description -Path $searchBase -ProtectedFromAccidentalDeletion $Protect
        }
    catch {
        Write-Host "OU already exists"
        }
}

$UserList = Import-Csv -Path $txt_csv.Text -Delimiter ";"

<# ------- CREATE USERS ------- #>
foreach ($User in $UserList) {

    $OU = $User.path
    $UPN = $User.UPN
    $Password = $User.password 
    $Detailedname = $User.firstname + " " + $User.Lastname 
    $UserFirstname = $User.Firstname 
    $FirstLetterFirstname = $UserFirstname.substring(0,1) 
    $SAM =  $User.UPN
    $Company = $User.company
    $Description = $User.description
    $AccountExpirationDate = $User.accountexpirationdate

    $params = @{ 'Name'=$Detailedname;
                 'SamAccountName'=$SAM;
                 'UserPrincipalName'=$UPN+'@test.nl';
                 'DisplayName'=$Detailedname;
                 'GivenName'=$UserFirstname;
                 'Surname'=$User.Lastname;
                 'AccountPassword'=(ConvertTo-SecureString $Password -AsPlainText -Force);
                 'Enabled'=$True;
                 'PasswordNeverExpires'=$True;
                 'Path'=$OU;
                 'Company'=$Company;
                 'Description'=$Description;
                 'AccountExpirationDate'=$AccountExpirationDate
                 'HomeDrive' = "H:"
                 'HomeDirectory' = "\\home\userdata$\$SAM"
                 'ProfilePath'="\\dc-test\User Profiles$\$SAM"                 
                }

    New-ADUser @params
}

我希望这个创建函数作为输出文件,例如在 txt 中。

这是我的 wpf 按钮对象:

$button_add.Add_Click({create})

当我点击按钮时,输出必须生成一个输出文件。我已经尝试了很多解决方案,例如:

创建 | out-file 但我没有得到我想要的信息:

来源:https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/out-file

可以这样做吗?

亲切的问候

【问题讨论】:

  • 但是你想要什么输出?举个例子吧?
  • 例如创建了什么数据,是创建成功还是失败。

标签: wpf powershell


【解决方案1】:

您需要执行以下操作:

"processing New-ADUser with $params" | Out-File log.txt -Append
try {
  New-ADUser @params
  "Created $UPN" | Out-File log.txt -Append
}
catch {
  $_ | Out-File log.txt -Append
}

或者您可以将 New-ADUser 的输出传递给 Out-File:

New-ADUser @params -PassThru | Out-File log.txt -Append

【讨论】:

  • 没问题,很高兴能帮上忙!
猜你喜欢
  • 2017-12-03
  • 2021-10-30
  • 2012-05-19
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多