【发布时间】:2020-06-19 01:12:15
【问题描述】:
我已经创建了一个启用基本身份验证的 powershell 脚本,我需要它来允许 winrm 在运行我们的一些较旧的 powershell 脚本时工作。
我现在需要做的是能够将此脚本调用为带有真假参数的函数。例如禁用或启用基本身份验证。
如何将此代码包装到一个函数中,以便我可以从其他 powershell 脚本调用它?
所以如果我向这个脚本发送命令,例如
basicauth($true) - 它将按原样运行脚本
basicauth($false - 将禁用基本身份验证
我可以为 false 的 true 发送到此时创建备用 if else 语句,但不确定如何将整个脚本包装到一个函数中。
为 powershell 的新手状态道歉,我花了一段时间才让这个脚本按原样工作。
param([switch]$Elevated)
# Get variables
$registryPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WinRM\Client"
$key1 = "AllowDigest"
$key2 = "AllowUnencryptedTraffic"
$key3 = "AllowBasic"
$off = "00000000"
$on = "00000001"
# enables admin privileges
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated)
{
'tried to elevate, did not work, aborting...'
}
else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
# checks if the registry path is available, before adding the registry key values
If (!(Test-Path $registryPath))
{
New-Item -Path $registryPath -Force | out-Null
New-ItemProperty -Path $registryPath -Name $key1 -Value $off -PropertyType DWORD -Force | Out-Null
New-ItemProperty -Path $registryPath -Name $key2 -Value $off -PropertyType DWORD -Force | Out-Null
New-ItemProperty -Path $registryPath -Name $key3 -Value $on -PropertyType DWORD -Force | Out-Null
#'registry key did not exist'
exit
}
Else
{
New-ItemProperty -Path $registryPath -Name $key1 -Value $off -PropertyType DWORD -Force | Out-Null
New-ItemProperty -Path $registryPath -Name $key2 -Value $off -PropertyType DWORD -Force | Out-Null
New-ItemProperty -Path $registryPath -Name $key3 -Value $on -PropertyType DWORD -Force | Out-Null
#'registry key exists'
exit
}
注意:现在我知道 Else 语句的值应为: Set-ItemProperty 尽管如果我将代码更改为具有 Set-ItemProperty 脚本不再工作,我让它工作的唯一方法是将它作为:新项目属性。没有什么意义,但它确实有效。
理想情况下,最好只更新当前的 powershell 脚本以使用现代身份验证,但它们有 100 个,所以对我来说并不是一个真正可行的选择。
任何帮助将不胜感激。
【问题讨论】:
-
测试开关是否存在:If ($elevated.IsPresent)
-
@RetiredGeek - 我重新表述了我最初的问题。
标签: powershell