从批处理文件调用时,Powershell问题创建New-Object

时间:2013-10-08 10:56:25

标签: .net powershell batch-file

我使用NextPVR在电视上录制一些节目,并有一个powershell脚本将录制的TS文件转换为MP4,用MetaX标记文件,然后将文件添加到iTunes。

完成录制后,NextPVR会自动调用名为PostProcessing.bat的批处理文件,并传递许多参数。在这个批处理文件中,我有以下命令来调用我的Powershell脚本:

::Place this batch file in "C:\Users\Public\NPVR\Scripts" 
@ECHO OFF
cd /d "%~dp0" 
SET parent=%~dp1
IF %parent:~-1%==\ SET parent=%parent:~0,-1%

:: Call PowerShell script to handle post processing.
powershell -ExecutionPolicy RemoteSigned -File "C:\Users\Steve\Dropbox\Applications\Scripts\NVPR.ps1" "%parent%" %1
EXIT

我认为这个脚本被称为本地系统,我认为这是导致我的主要问题。我有以下功能,在我自己运行时效果很好,但在通过批处理文件调用时失败:

function addToiTunes($path) {
    # get reference to the running iTunes
    $iTunes = New-Object -ComObject iTunes.application
    $LibrarySource = $iTunes.LibrarySource
    foreach ($pList in $LibrarySource.Playlists) {
        if ($pList.Name -eq "Library") {
            $playList = $pList
            Break
        }
    }
    try {
        $playList.AddFile($path)
    } catch {
        return $false
    }
    return $true
}

有没有办法可以将PS1作为当前登录用户调用而无需使用凭据等,或者我可以将ComObject附加到在登录用户下运行的进程吗?

2 个答案:

答案 0 :(得分:0)

我想你可能在错误的地方寻找你的问题。

批处理文件以及从它们运行的​​后续powershell脚本会收到调用它们的用户的权限。如果您在Windows或Windows上,您可能会受到Windows安全性的攻击,但您可以通过右键单击批处理并点击“以管理员身份运行”或打开admin cmd提示并从那里运行批处理来避免这种情况。

您可以将其作为另一个进程打开的唯一方法是将批处理文件计划到任务并将runas用户设置为SYSTEM。但就像我说的那样,如果您以具有适当权限的用户身份登录,则不应该有任何问题。

答案 1 :(得分:0)

好的,所以我几乎回答了我自己的问题。我最终创建了另外两个脚本,一个用于创建安全密码并将其存储到PC:

$password = Read-Host "Please enter a password to be encrypted:" -AsSecureString
$path = Read-Host "Please enter a path where pwd.txt is to be stored:"
If ($path[-1] -ne "\") {
    $path += "\"
}
$path += "pwd.txt"
ConvertFrom-SecureString $password | Out-File $path

还有第二个可以从文件中获取凭据,并启动传递给它的脚本(Params的处理还没有工作,但我越来越近了):

# Get parameter credentials
$username = $args[0]
$passwordPath = $args[1]
$scriptToRun = $args[2]
$param1 = $args[3]
$param2 = $args[4]
$param3 = $args[5]
$param4 = $args[6]
$param5 = $args[7]
$param6 = $args[8]

# Collect arguments into a single array.
$arguments = @()
if ($param1 -ne $null) {$arguments += $param1}
if ($param2 -ne $null) {$arguments += $param2}
if ($param3 -ne $null) {$arguments += $param3}
if ($param4 -ne $null) {$arguments += $param4}
if ($param5 -ne $null) {$arguments += $param5}
if ($param6 -ne $null) {$arguments += $param6}

# Set credentials and launch passed script.
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString (Get-Content $passwordPath)))
Invoke-Command -FilePath $scriptToRun -Credential $cred -ComputerName localhost -ArgumentList $arguments