我写了一个自定义的写日志功能。如果我在Invoke中使用Write-Log函数,则会收到以下错误消息“远程执行时出错:术语'Write-Log'未识别为cmdlet,函数,脚本文件或可运行程序的名称。检查名称的拼写,或者是否包含路径,请验证路径是否正确,然后重试。”
我正在使用Powershell 5.1。我确实尝试使用$ {function:Write-Log},但没有用。
Function Write-Log([string]$ComputerList,$message, $level="INFO") {
$date_stamp = Get-Date -Format s
$log_entry = "$date_stamp - $level - $message"
$log_file = "$tmp_dir\upgrade_powershell.log"
Write-Verbose -Message $log_entry
Add-Content -Path $log_file -Value $log_entry
}
Function Start-Process ($ComputerList) {
Return Invoke-Command -computername $Computer -ScriptBlock {
Param($file)
$Application = $args[0]
$ApplicationName = $Application.Substring($Application.LastIndexOf('\')+1)
$ApplicationFolderPath = $Application.Substring(0,$Application.LastIndexOf('\'))
$ApplicationExt = $Application.Substring($Application.LastIndexOf('.')+1)
Write-Log -message "Installing $file on $($env:COMPUTERNAME)"
$p = Start-Process $file -Wait -Passthru
$p.WaitForExit()
$p.WaitForExit()
if ($p.ExitCode -ne 0) {
Write-Log -message "Failed installing with error code $($p.ExitCode)" -level "ERROR"
$Return = $($env:COMPUTERNAME)
}
else{
$Return = 0
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) {
$log_msg = "$($error_msg): exit code $p.ExitCode"
Write-Log -message $log_msg -level "ERROR"
#throw $log_msg
return
}
if ($p.ExitCode-eq 3010) {
Reboot-AndResume
break
}}
}
}
答案 0 :(得分:0)
尝试在脚本块中包含自定义函数定义,类似这样
invoke-command -scriptblock {
param (
your params
)
begin {
function write-log (etc) {
the function code
}
}
process {
your main scriptblock stuff
}
end {}
}
答案 1 :(得分:0)
我确实尝试使用
PERMISSION DENIED
,但是没有用。
${function:Write-Log}
使用namespace variable notation获取${function:Write-Log}
函数的 body 作为 script块 。
由于您使用的是 remoting (您将Write-Log
参数传递给-ComputerName
),因此要么必须将该脚本块作为参数到远程执行的脚本块,或者-更方便地-利用$using:
scope(PSv3 +)使 local 变量值 remotely < / em> 。
不幸的是,从Windows PowerShell v5.1 / PowerShell Core 6.2.0开始,Invoke-Command
不能与命名空间变量符号结合使用-请参见this GitHub issue。
因此,存在错误的情况下,将脚本块引用为$using:
不会直接起作用,但可以使用中间变量,然后使用使用简化的方案来适应this excellent answer:
注意:要运行此代码(通过连接到同一台计算机来模拟远程处理),请确保您计算机上的remoting is enabled,然后以管理员身份调用代码 。
${using:function:Write-Log}
以上内容应返回function Write-Log {
param([string] $ComputerList, $message, $level="INFO")
# For testing simply echo the arguments
"$ComputerList, $message, $level"
}
# Recreate the function's full source code as a string.
$funcDef = "function Write-Log { ${function:Write-Log} }"
Invoke-Command -Computer . -ScriptBlock {
# Define the Write-Log function using Invoke-Expression
# Note: This is a rare case where use of Invoke-Expression is
# justified; generally, it is to be AVOIDED - see
# https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/
Invoke-Expression $using:funcDef
# Now you can call it as you would locally.
Write-Log 'ws1 ws2' testing DEBUG
}
。
当然,如果ws1 ws2, testing, DEBUG
源代码是:
您可以使函数定义成为远程执行脚本块的一部分:
Write-Log