下面的两个代码可以独立工作,但它们不能在同一个脚本中工作。我真的需要帮助,肯定有不相容的地方。
我的脚本的第一部分使用InvokeCimMethod来启用PSRemoting,它很有效。
变量
$hostname = 'PC1'
$Session = New-PSSession $hostname
$DestinationPath = "C:windowstemp"
第1部分
$SessionArgs = @{
ComputerName = $hostname
Credential = $credential
SessionOption = New-CimSessionOption -Protocol Dcom
}
$MethodArgs = @{
ClassName = 'Win32_Process'
MethodName = 'Create'
CimSession = New-CimSession @SessionArgs
Arguments = @{
CommandLine = "powershell Start-Process powershell -ArgumentList 'Enable-PSRemoting -Force'"
}
}
Invoke-CimMethod @MethodArgs
如果上面的第一部分不存在,我的代码的第二部分就可以工作。它是创建一个TEMP文件夹,然后将整个文件夹复制到TEMP.中
第2部分
Invoke-Command -Session $Session -ScriptBlock { Param($Destination) New-Item -Path $Destination -ItemType Directory -ErrorAction SilentlyContinue} -ArgumentList $DestinationPath
Copy-Item -Path "\sharedfolderfoobar" -ToSession $Session -Destination "C:windowstemp" -recurse -force
错误
Copy-Item : The runspace state is not valid for this operation.
奇怪的是,我已经将InvokeCimMethod插入到许多其他做类似事情的脚本中,并且它运行良好,例如
其工作示例
$env:hostname
$env:process
$SessionArgs = @{
ComputerName = $env:hostname
Credential = $credential
SessionOption = New-CimSessionOption -Protocol Dcom
}
$MethodArgs = @{
ClassName = 'Win32_Process'
MethodName = 'Create'
CimSession = New-CimSession @SessionArgs
Arguments = @{
CommandLine = "powershell Start-Process powershell -ArgumentList 'Enable-PSRemoting -Force'"
}
}
Invoke-CimMethod @MethodArgs
$session = New-PSSession $env:hostname
ipconfig
Invoke-Command -Session $session -ScriptBlock {param($process) Stop-Process -ProcessName $process -Force} -ArgumentList $env:process
$Session | Remove-PSSession
请帮忙!我什么都试过了,甚至试过Get-CimSession|Remove-CimSession,但都没用。为什么它不兼容?
Invoke Command-Session$Session-ScriptBlock{New Item-Path$using:DestinationPath-ItemType Directory-ErrorAction SilentlyContinue}
我可以通过放入变量来解决这个问题
$Session = New-PSSession $hostname
就在Invoke-Command
之前(而不是在脚本的顶部(,因为我认为当我发送Enable-PSRemoting
时,它会重置连接。