You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为C#调用的PowerShell命令设置默认确认输入为YES

解决方案

方案1:修改PowerShell脚本(最简便)

Start-CosmosDbEmulator命令默认会触发操作确认提示,添加参数强制跳过确认即可适配无交互运行场景,修改后的脚本如下:

Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator -Confirm:$false -Force

参数说明:

  • Confirm:$false 强制关闭命令的确认提示
  • Force 跳过所有前置检查类的二次确认,适配服务器无交互运行环境

方案2:修改C#调用逻辑(无需改动PS脚本)

如果不方便修改PowerShell脚本,可以在C#调用时全局设置PowerShell的确认偏好,同时额外添加执行策略绕过配置,避免服务器上默认执行策略限制脚本运行,修改后的C#代码如下:

public void CreateDatabaseFromPowerShell()
{
    string path = Path.Combine(Root, @"TestData\CosmosScript.ps1");
    // 初始化会话状态,设置执行策略为绕过,避免脚本被系统默认策略拦截
    InitialSessionState initial = InitialSessionState.CreateDefault();
    initial.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
    Runspace runspace = RunspaceFactory.CreateRunspace(initial);
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    // 先设置全局确认偏好为无,跳过所有命令的确认提示
    pipeline.Commands.AddScript("$ConfirmPreference = 'None'");
    pipeline.Commands.AddScript(path);
    Collection<PSObject> results = pipeline.Invoke();
    runspace.Close();           
}

注意:服务器上运行时需要保证执行该代码的进程有管理员权限,否则Cosmos DB模拟器启动本身会因权限不足失败,和确认提示无关。

内容的提问来源于stack exchange,提问作者ZZZSharePoint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 11:24:04