带有 Import-Module 的 Powershell 运行脚本

标签 powershell powershell-module

我为我的管理员组创建了一个模块,其中包含一些自动化我们通常执行的一些程序的功能(将管理员添加到远程机器、C 驱动器清理等......)

这些功能的先决条件之一是生成一系列 7 个凭证,一个用于我们工作的每个域。

有没有办法在导入模块时运行脚本 block ,或者这是我应该添加到每个人的个人资料中的东西?

一位评论者提到我可以将它添加到 module.psm1 文件中,但这不起作用。这是我要运行的代码。

$creds = Import-Csv [csvfile]
$key = Get-Content [keyfile]
foreach ($cred in $creds) {
    $user = $cred.User
    $password = $cred.Hash | ConvertTo-SecureString -Key $key
    $i = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$password
    New-Variable -Name ($cred.Domain + "_Cred") -Value $i -Force
    }

手动运行它可以正常工作,但从 Import-Module 命令运行时不会创建凭据。

最佳答案

导入模块时,任何不是函数的代码都会运行。

关于带有 Import-Module 的 Powershell 运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879818/

相关文章:

powershell - 如何使 powershell cmdlet 静音?

sharepoint - 从存储在文档库中的 Excel 中获取数据并使用 powershell 将其显示在列表中

multithreading - 从运行空间内的模块调用函数

powershell - 如何拥有父脚本但保持与 Powershell 脚本的关注点分离?

powershell - 为所有用户持久安装 PowerShell 模块

模块中的 PowerShell .ps1 文件 cmdlet

sql - Azure SQL DB : create users with PowerShell, 参数化 SQL 脚本和 Azure Key Vault

powershell - 如何从资源管理器 PSSession VM?

powershell - 在 Powershell 中使用 SOAP 渲染带有参数的 SSRS 报告

具有在单独文件中定义的类的 PowerShell 模块未通过 GitHub Actions 中的 Pester 测试