标签: powershell

Windows Powershell 在网络适配器上设置 IP 地址

我需要能够带上我的笔记本电脑并插入多个位置的多个不同网络。每个网络都要求我使用一个静态地址。我目前有一个 shell 脚本,提示输入网络位置并使用 netsh 设置 IP 地址。但是,Microsoft 警告说他们可能会删除 netsh 并使用 Powershell,因此我尝试在 Powershell 中重新创建我的脚本。

我遇到的问题是,如果我从 dhcp 转到静态地址,我可以使用:

New-NetIPAddress -InterfaceAlias $myAdapter -AddressFamily IPv4 10.1.2.3 -PrefixLength 24 -Type Unicast -DefaultGateway 10.1.2.1
Run Code Online (Sandbox Code Playgroud)

但是,当使用 New-NetIPAddress 从一个静态地址到另一个静态地址时,只需向适配器添加另一个 IP 地址(而且我无法连接到任何东西,因为它似乎只使用第一个 IP 地址)。为了解决这个问题,我可以使用 Set-NetIPAddress,但这似乎不接受 -DefaultGateway 参数,因此我分配了新地址,但使用了旧网关。我尝试使用 Remove-NetIPAddress,但这似乎保留了网关参数,因此 New-NetIPAddress 命令失败并显示“Instance DefaultGateway already exists”。如何删除网关以便我可以使用 New-NetIPAddress 重新开始或在使用 Set-NetIPAddress 时替换网关?

windows powershell networking

3
推荐指数
1
解决办法
6594
查看次数

如何在 Powershell 中为命令“ls -lrt”设置别名

这可能是我缺少的一些简单解决方案。我想别名命令行:

> ls -lrt
Run Code Online (Sandbox Code Playgroud)

要真正做到这一点:

> Get-ChildItem | Sort-Object -Property LastWriteTime
Run Code Online (Sandbox Code Playgroud)

我看到的问题ls是 已经别名为Get-Children并且在我进行任何尝试之前解决了,例如:

New-Alias -Name 'ls -lrt' -Value 'Get-ChildItem | Sort-Object -Property LastWriteTime'
Run Code Online (Sandbox Code Playgroud)

有没有人知道一种方法可以在不损害以前存在的别名的情况下做到这一点ls?

powershell

3
推荐指数
1
解决办法
3134
查看次数

Register-PsRepository : 在此对象上找不到属性“名称”

尝试运行 Register-PsRepository 时出现以下错误

我试过了:

  • 重新安装 WMF 5、PowerShellGet 和 PackageManagement 模块
  • 更新所述模块
  • 调试 PowerShellGet 模块我可以看到 PsBoundParameters 确实将 Name 值传递给 Register-PackageSource 命令。
  • 当我手动运行 Register-PackageSource 时,它​​确实可以正常工作。

有任何想法吗?

PS C:\> Register-PSRepository -Name MyRepo -SourceLocation  https://MyRepo.com/api/Myrepo   -Credential $c
PackageManagement\Register-PackageSource : The property 'Name' cannot be 
found on this object. Verify that the property exists.
At C:\Program  Files\WindowsPowerShell\Modules\PowerShellGet\1.6.0\PSModule.psm1:4631 char:17
Run Code Online (Sandbox Code Playgroud)

powershell powershellget

3
推荐指数
1
解决办法
1752
查看次数

检查天蓝色存储 powershell 中是否存在表

我有这个 powershell,我想用它在 azure 存储帐户中创建新表。

Param(
 [string]$rgName,
 [string] $tableName
 )
 $storcontext= New-AzureStorageContext -ConnectionString '$(MyConnectionString)'

if(!(Get-AzureStorageTable -Name $tableName -Context $storcontext ))
 {
   New-AzureStorageTable -Name $tableName -Context $storcontext
 }
Run Code Online (Sandbox Code Playgroud)

New-AzureStorageTable 命令工作正常。但是我尝试添加检查以查看表是否已存在。但是在 Get 命令上,powershell 提示我说表不存在。

我想要做的是检查表是否存在,如果不存在,则创建它。

还有另一种方法吗?

powershell azure azure-storage azure-powershell

3
推荐指数
1
解决办法
1305
查看次数

在此处字符串标头之后但在行尾之前不允许使用任何字符

我在我的脚本中使用这个 aa 基础:

https://www.nwcadence.com/blog/vststfs-rest-api-the-basics-and-working-with-builds-and-releases

我的脚本如下

Param(
   [string]$vstsAccount = "abc",
   [string]$projectName = "abc",
   [string]$user = "",
   [string]$token = "xyz"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$verb = "POST"


$body = @"{

    "definition": {
         "id": 20
    }
}"@


$uri = "https://$($vstsAccount).visualstudio.com/DefaultCollection/$($projectName)/_apis/build/builds?api-version=4.1"
$result = Invoke-RestMethod -Uri $uri -Method $verb -ContentType "application/json" -Body (ConvertTo-Json $body)  -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
Run Code Online (Sandbox Code Playgroud)

但是我在上面的博客文章中使用的主体定义存在语法错误。

> o characters are allowed after a here-string header but before the end
> of …
Run Code Online (Sandbox Code Playgroud)

rest powershell azure-devops

3
推荐指数
2
解决办法
8817
查看次数

Inserting Delimiter into PowerShell Output

The result of Get-Process -Name explorer | select Handles,WS,CPU,Id,ProcessName | ft -HideTableHeaders returns the following output:

2623 255336448 178.125 10080 explorer 
Run Code Online (Sandbox Code Playgroud)

In order to ingest this data into a third party system, I need to pipe delimit the result as such:

2623|255336448|178.125|10080|explorer 
Run Code Online (Sandbox Code Playgroud)

What is the best way to achieve this?

powershell

3
推荐指数
1
解决办法
1933
查看次数

Powershell [System.IO.Compression.ZipArchiveEntry] 不包含名为“ExtractToFile”的方法

我有一个 powershell 脚本,我想在其中提取特定条目。我似乎无法弄清楚如何解决在 .NET ZipArchiveEntry 对象上找不到扩展方法的错误。

我下面的脚本将运行并从 zip 中“写出”文件,但是当它到达$entry.ExtractToFile($dst)行时,它会产生以下错误:

方法调用失败,因为 [System.IO.Compression.ZipArchiveEntry] 不包含名为“ExtractToFile”的方法。

Add-Type -AssemblyName System.IO.Compression -ErrorAction Stop
Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop

$filesToExtract = @(
    "appsettings.json";
    "Content\cms\index.xml";
)
$archive = "C:\Users\User1\Desktop\archive.zip"
$dstRoot = "C:\Users\User1\Desktop\test"
$zip = [IO.Compression.ZipFile]::OpenRead($archive)
foreach($entry in $zip.Entries){
    if ($filesToExtract -contains $entry.FullName){
        $dst = [io.path]::combine($dstRoot, $entry.FullName)
        %{ "Extract ==> " + $dst }        

        $entry.ExtractToFile($dst)

    }
}
$zip.Dispose()
Run Code Online (Sandbox Code Playgroud)

.net powershell scripting

3
推荐指数
1
解决办法
1855
查看次数

在 PowerShell 中迭代 JSON 并删除 JSON 元素

下面粘贴的是我的示例 JSON 文件。

  1. 循环所有 unqiue 属性
  2. 对于每个唯一的属性,检查 "x-visibility": "Private" 对象的值。如果这是“私人”,则删除整个对象。

我正在尝试这样做

foreach ($p in $apijson.paths.PSObject.Properties.Value) {
    $get = $p.get.'x-qlik-visibility' -eq 'Private'

    if ($get -eq 'True') {
        Write-Host 'Removing Object  :'$p
        # Remove-ItemProperty -Name $p.get
        $apijsonNew.PSObject.Properties.Remove($p)
    }
}
Run Code Online (Sandbox Code Playgroud)
{
  "swagger": "2.0",
  "info": {
    "title": "Open API specification for Repository Main API",
    "version": "20.8.0"
  },
  "basePath": "/qrs",
  "schemes": [
    "https"
  ],
  "paths": {
    "/about/api/default/analyticconnection": {
      "get": {
        "operationId": "2b781738-afd0-37a9-4248-84ec8d6be58c",
        "parameters": [
          {
            "name": "listentries",
            "in": "query",
            "required": false,
            "default": true,
            "type": "boolean", …
Run Code Online (Sandbox Code Playgroud)

powershell json

3
推荐指数
2
解决办法
9697
查看次数

Golang 调用 PowerShell.exe 总是返回 ASCII 字符

我正在使用 Go 编写的应用程序中的 PowerShell,但无法让它返回非 ASCII 字符。起初我使用 go-powershell,但遇到同样的问题:https : //github.com/gorillalabs/go-powershell/issues/10,现在使用稍微更基本的方法:

package main

import (
        "bytes"
        "fmt"
        "os/exec"
)

type PowerShell struct {
        powerShell string
}

func New() *PowerShell {
        ps, _ := exec.LookPath("powershell.exe")
        return &PowerShell{
                powerShell: ps,
        }
}

func (p *PowerShell) Execute(args ...string) (stdOut string, stdErr string, err error) {
        args = append([]string{"-NoProfile", "-NonInteractive"}, args...)
        cmd := exec.Command(p.powerShell, args...)

        var stdout bytes.Buffer
        var stderr bytes.Buffer
        cmd.Stdout = &stdout
        cmd.Stderr = &stderr

        err = cmd.Run()
        stdOut, stdErr = stdout.String(), …
Run Code Online (Sandbox Code Playgroud)

powershell go

3
推荐指数
1
解决办法
4948
查看次数

方法调用失败,因为 [System.Management.Automation.PSObject] 不包含名为“op_Addition”的方法

我正在尝试将共享点列表中的一些数据导出到 csv,但出现此错误:

$ListItemCollection | 导出-CSV "D:\LX.csv" -NoTypeInformation

Method invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'.
At line:20 char:2
+     $ListItemCollection += $ExportItem
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
Run Code Online (Sandbox Code Playgroud)

代码很简单

$URL = "https://mysite"
$List = "Page Contents"

$Web = Get-SPWeb $URL

$web
$spList = $Web.Lists[$List]
$Items = $spList.GetItems()


$listItems = $spList.Items

foreach($item in $listItems) {

    $ExportItem = New-Object PSObject 
    $ExportItem | Add-Member -MemberType NoteProperty -name "PageID" -value $item["PageID"]
    $ExportItem | Add-Member …
Run Code Online (Sandbox Code Playgroud)

powershell sharepoint

3
推荐指数
1
解决办法
2万
查看次数