1.直接输出为json格式:

Get-Process -Id $pid  | ConvertTo-Json | clip.exe

2.自定义结果为json格式:

 $serverinfoj = @"
{
"Status": "Success",
"Infors": {
"ServerName": "$env:ComputerName",
"IP": "$Server",
"OSVersion": "$osversion",
"MemorySize": "$memorysize_sum",
"CPU": "$cpunamecore",
"DomainName": "$domainname",
"DISK": "$disklist",
"SN": "$sn",
"Xinghao":"$xinghao"
}
}
"@
#格式必须要这样,顶格写,开头和结尾的@不能与大括号写到一行
#其中的变量内容也必须要引起来
$serverinfo = ConvertFrom-Json -InputObject $serverinfoj #转换为json格式
$serverinfo.Status
$serverinfo.Infors
$serverinfo.Infors.OSVersion #输出结果:
ServerName : PC-L
IP : 10.16.30.51
OSVersion : Microsoft Windows Server 2012 R2 Datacenter 64bit
MemorySize : 4GB
CPU : Intel(R) Xeon(R) CPU E5-2620 v3 @ 2.40GHz 2*1C
DomainName : uxin.youxinpai.com
DISK : Disk0:300GB
SN : Hyper-V
Xinghao : Microsoft Virtual Machine Microsoft Windows Server 2012 R2 Datacenter 64bit

还可以对$serverinfo内容进行修改,如:

$serverinfo.Status = "test"

value也可以直接通过命令获得,使用$符号

$json = @"
{
"ServerName": "$env:ComputerName",
"BIOS": {
"sn" : "$((Get-WmiObject -Class Win32_BIOS).sn)",
"Version" : "$((Get-WmiObject -Class Win32_BIOS).Version)"
},
"OS" : "$([Environment]::OSVersion.VersionString)"
}
"@
$data = (New-Object PSObject |
Add-Member -PassThru NoteProperty ServerName "nnn" |
Add-Member -PassThru NoteProperty Infors "192.168.1.1"
) | ConvertTo-JSON #返回是json字符串,等同于@""@方法

 后端API,通过GET方法接收URL参数:

def srvinfors_api(request): #Client access this api to write server infors.
if request.method == 'GET':
Infors=request.GET['Infors']
cj = json.loads(Infors,strict=False,encoding='utf-8') #将参数转换为dict
cjres = json.dumps(cj,ensure_ascii=False) #返回时使用json字符串
print cj['ServerName']
#serverinfors.objects.update_or_create(IP=cj['IP'],defaults=cj)
return HttpResponse(cjres)

提交参数:http://10.160.25.48/sinfors/srvinfors_api/?a=2&b=3&c=22

在PowerShell3.0中使用invoke-restmethod提交参数,(invoke-webrequest返回格式是对象,invoke-restmethod返回格式是字符串)

$a='adf'
$h=@{a=$a;
b=222;
c=""
} $url = "http://10.160.25.48/sinfors/srvinfors_api" invoke-restmethod -Uri $url -body $h

参数中还可以包含json格式数据:

$a='adf'

$data=@{a=$a;
b=222;
c=@"
{"ServerName": "$env:ComputerName","IP": "$Server"}
"@
} $url = "http://10.160.25.48/sinfors/srvinfors_api" invoke-restmethod -Uri $url -body $data

Python API中取参数c的字段值:

json.loads(c)['ServerName']

示例:将计算机硬件信息提交到API,该API可以将数据写入到数据库中(PS3.0):

$system = Get-WmiObject -Class Win32_ComputerSystem

#获取计算机域名、型号
$domainname = $system.Domain
$model = $system.Model #获取计算机IP地址,取IP和gw不为空的网卡IP地址
$Server = (gwmi Win32_NetworkAdapterConfiguration |?{ $_.DefaultIPGateway -ne $null}).IPAddress[0] #获取操作系统版本
$os = Get-WmiObject -Class Win32_OperatingSystem #获取操作系统版本
$os_caption = $os.Caption
If ($os_caption.Contains("Server 2008 R2 Enterprise"))
{$os_caption_s = "Win2008"}
ElseIf ($os_caption.Contains("Server 2003 Enterprise"))
{$os_caption_s = "Win2003"}
Else {$os_caption_s = $os.Caption}
$osversion = $os_caption_s + " " + $os.OSArchitecture.Substring(0,2) + "bit" #获取CPU名称、单颗CPU核心数量*CPU个数
$cpus = Get-WmiObject -Class win32_processor
$cpucount = 0
Foreach ($cpu in $cpus)
{
If ($cpu.DeviceID -ne $null)
{$cpucount += 1}
}
$cpunamecore = $cpu.name+""+[string]$cpu.NumberOfLogicalProcessors + '*' + [string]$cpucount + "C" #获取内存大小
$memorys = Get-WmiObject -Class Win32_PhysicalMemory
#$memorylist = $null
$memorysize_sum = $null
Foreach ($memory in $memorys)
{
#$memorylist += ($memory.capacity/1024/1024/1024).tostring("F1")+"GB + "
[int]$memorysize_sum_n += $memory.capacity/1024/1024/1024
}
$memorysize_sum = [string]$memorysize_sum_n + "GB" #获取磁盘信息
$disks = Get-WmiObject -Class Win32_Diskdrive
$disklist = $null
#$disksize_sum = $null
Foreach ($disk in $disks)
{
$disklist += ($disk.deviceid.replace("\\.\PHYSICALDRIVE","Disk") +":" + [int]($disk.size/1024/1024/1024)+"GB ")
#$disksize_sum+=$disk.size
} #获取计算机序列号、制造商
$bios = Get-WmiObject -Class Win32_BIOS
$sn = $bios.SerialNumber
If ($sn.Substring(0,6) -eq "VMware")
{$sn = "VMware"}
If ($bios.Manufacturer.contains("Dell"))
{$manufacturer = "Dell"}
Elseif ($bios.Manufacturer.contains("HP"))
{$manufacturer = "HP"}
Elseif ($bios.Manufacturer.contains("Microsoft"))
{
$manufacturer = "Microsoft"
$sn = ""
}
Else {$manufacturer = $bios.Manufacturer}
$type = $manufacturer + " " + $model
if ($type.contains("Microsoft Virtual Machine"))
{$type = "Hyper-V"} $serverinfoj = @{
Status="Success";
Infors= @"
{"ServerName": "$env:ComputerName","IP": "$Server","OSVersion": "$osversion","MemorySize": "$memorysize_sum", "CPU": "$cpunamecore","DomainName": "$domainname","DISK": "$disklist","SN": "$sn","Type":"$type"}
"@
} $url = "http://10.160.25.48/sinfors/srvinfors_api" invoke-restmethod -Uri $url -body $serverinfoj

返回值:

ServerName : PC-L
IP : 192.168.50.74
OSVersion : Microsoft Windows 10 企业版 64bit
MemorySize : 64GB
CPU : Intel(R) Core(TM) i7-5500U CPU @ 2.40GHz4*1C
DomainName : WORKGROUP
DISK : Disk0:932GB
SN : FY5DZ32
Type : Dell Inspiron 5448

示例:将计算机硬件信息提交到API,该API可以将数据写入到数据库中(PS2.0):

#客户端运行该脚本,将信息写入到数据库中,适用于PS2.0及其以上

$system = Get-WmiObject -Class Win32_ComputerSystem

#获取计算机域名、型号
$domainname = $system.Domain
$model = $system.Model #获取计算机IP地址,取IP和gw不为空的网卡IP地址
$Server = (gwmi Win32_NetworkAdapterConfiguration |?{ $_.DefaultIPGateway -ne $null}).IPAddress[0] #获取操作系统版本
$os = Get-WmiObject -Class Win32_OperatingSystem #获取操作系统版本
$os_caption = $os.Caption
If ($os_caption.Contains("Server 2008 R2 Enterprise"))
{$os_caption_s = "Win2008"}
ElseIf ($os_caption.Contains("Server 2003 Enterprise"))
{$os_caption_s = "Win2003"}
Else {$os_caption_s = $os.Caption}
$osversion = $os_caption_s + " " + $os.OSArchitecture.Substring(0,2) + "bit" #获取CPU名称、单颗CPU核心数量*CPU个数
$cpus = Get-WmiObject -Class win32_processor
$cpucount = 0
Foreach ($cpu in $cpus)
{
If ($cpu.DeviceID -ne $null)
{$cpucount += 1}
}
$cpunamecore = $cpu.name+""+[string]$cpu.NumberOfLogicalProcessors + '*' + [string]$cpucount + "C" #获取内存大小
$memorys = Get-WmiObject -Class Win32_PhysicalMemory
#$memorylist = $null
$memorysize_sum = $null
Foreach ($memory in $memorys)
{
#$memorylist += ($memory.capacity/1024/1024/1024).tostring("F1")+"GB + "
[int]$memorysize_sum_n += $memory.capacity/1024/1024/1024
}
$memorysize_sum = [string]$memorysize_sum_n + "GB" #获取磁盘信息
$disks = Get-WmiObject -Class Win32_Diskdrive
$disklist = $null
#$disksize_sum = $null
Foreach ($disk in $disks)
{
$disklist += ($disk.deviceid.replace("\\.\PHYSICALDRIVE","Disk") +":" + [int]($disk.size/1024/1024/1024)+"GB ")
#$disksize_sum+=$disk.size
} #获取计算机序列号、制造商
$bios = Get-WmiObject -Class Win32_BIOS
$sn = $bios.SerialNumber
If ($sn.Substring(0,6) -eq "VMware")
{$sn = "VMware"}
If ($bios.Manufacturer.contains("Dell"))
{$manufacturer = "Dell"}
Elseif ($bios.Manufacturer.contains("HP"))
{$manufacturer = "HP"}
Elseif ($bios.Manufacturer.contains("Microsoft"))
{
$manufacturer = "Microsoft"
$sn = ""
}
Else {$manufacturer = $bios.Manufacturer}
$type = $manufacturer + " " + $model
if ($type.contains("Microsoft Virtual Machine"))
{$type = "Hyper-V"} $Status = @"
{Status:"Success"}
"@ $Infors= @"
{"ServerName": "$env:ComputerName","IP": "$Server","OSVersion": "$osversion","MemorySize": "$memorysize_sum", "CPU": "$cpunamecore","DomainName": "$domainname","DISK": "$disklist","SN": "$sn","Type":"$type","OS_mark":"wa"}
"@ $postdata = "/?Status=" + $Status + "&Infors=" + $Infors $url = "http://10.160.25.48/sinfors/srvinfors_api"
$uri = $url + $postdata #调用WebRequest方法访问接口
$request = [System.Net.WebRequest]::Create($uri)
$request.KeepAlive = $false
$request.AllowAutoRedirect=$false
$request.Method="GET" #输出接口返回结果
$response = $request.GetResponse()
$stream = $response.GetResponseStream()
$reader = New-Object IO.StreamReader($stream)
$html = $reader.ReadToEnd()
Write-Host $html #clean up resources
$reader.Close()
$stream.Close()
$response.Close()

#返回值:

{"DISK": "Disk0:200GB ", "DomainName": "u.com", "IP": "10.16.2.4", "ServerName": "MGMT", "MemorySize": "12GB", "SN": "", "OS_mark": "wa", "OSVersion": "Microsoft Windows Server 2012 R2 Datacenter 64bit", "Ty
pe": "Hyper-V", "CPU": "Intel(R) Xeon(R) CPU E5-2620 v3 @ 2.40GHz4*1C"}

###############################

在PowerShell2.0下没有invoke-restmethod命令可用,可以调用相应的静态类实现,通过拼接字符串方式提交参数:

1.调用System.Net.WebRequest类:

$Status = @"
{Status:"Success"}
"@ $Infors= @"
{"ServerName": "ComputerName","IP": "192.168.1.1"}
"@ $postdata = "/?Status=" + $Status + "&Infors=" + $Infors $url = "http://10.160.25.48/sinfors/srvinfors_api"
$uri = $url + $postdata #调用WebRequest方法访问接口
$request = [System.Net.WebRequest]::Create($uri)
$request.KeepAlive = $false
$request.AllowAutoRedirect=$false
$request.Method="GET" #输出接口返回结果
$response = $request.GetResponse()
$stream = $response.GetResponseStream()
$reader = New-Object IO.StreamReader($stream)
$html = $reader.ReadToEnd()
Write-Host $html #clean up resources
$reader.Close()
$stream.Close()
$response.Close() #必须要close,否则response资源不释放,调用多次后后会出现超时。http://www.ravichaganti.com/blog/handling-system-net-webrequest-getresponse-timeout-in-powershell/

2.调用System.Net.WebClient类:

$data=@"
{"ServerName":"nnn","Infors":"192.168.1.1"}
"@ $url = "http://10.160.25.48/sinfors/srvinfors_api/?Infors="+$data
$webclient = New-Object System.Net.WebClient $webClient.DownloadString($url) #| ConvertFrom-Json

webrequest后端接收不到数据,还有问题。。。。:

$url = "http://10.160.25.48/sinfors/srvinfors_api"
$request = [Net.WebRequest]::Create($url) $request.ServicePoint.Expect100Continue = $false $request.ContentType = "application/json"
$request.Method = "POST" $data = (New-Object PSObject |
Add-Member -PassThru NoteProperty ServerName "nnn" |
Add-Member -PassThru NoteProperty Infors "192.168.1.1"
) | ConvertTo-JSON $bytes = [System.Text.Encoding]::UTF8.GetBytes($data) $request.ContentLength = $bytes.Length $requestStream = [System.IO.Stream]$request.GetRequestStream()
$requestStream.write($bytes, 0, $bytes.Length)
$requestStream.Close()
$response = $request.GetResponse()

查询IP所在地:

 $ip="61.135.169.121"
$ipSvc= 'http://ip.taobao.com/service/getIpInfo.php?ip='+ $ip # 向IP地址服务发送Rest请求
$r = Invoke-RestMethod $ipSvc
$r.data |Select country,region,city,isp

接口调用,输出结果为Json格式(ConvertTo-Json),提交参数给URL(WebRequest)的更多相关文章

  1. python json.dumps()函数输出json格式,使用indent参数对json数据格式化输出

    在python中,要输出json格式,需要对json数据进行编码,要用到函数:json.dumps json.dumps() :是对数据进行编码 #coding=gbkimport json dict ...

  2. Js数据类型、Json格式、Json对象、Json字符串

    数据类型,从结构上看,所有的数据最终都可以分成三种类型: 第一种类型是scalar(标量),也就是一个单独的string(字符串)或数字(numbers),比如“北京”这个单独的词. 第二种类型是se ...

  3. 超简单的处理JSON格式和JSON数组格式的String

    现在网站上有不少处理JSON格式的工具类,但是我找了一天,发现大都是需要编写相应对象类来进行处理,比较麻烦,比如:Gson,json-lib.Gson,json-lib这些处理那些接口之类的参数名字和 ...

  4. js字符串转json格式与json对象转字符串

    json字符串----->json对象json对象------>json字符串 使用JSON.parse()函数 this.dataList = JSON.parse(dataList); ...

  5. js判断字符串是否为正确的JSON格式及JSON格式化的实现

    判断是否是正确的JSON格式 function isJSON(str) { if (typeof str == 'string') { try { var obj=JSON.parse(str); i ...

  6. python json.dumps()函数输出json格式,使用ensure_ascii参数对中文输入的支持

    在python使用过程中,输入中文,不能正常的输出,可以使用ensure_ascii参数来解决不能输入中文的问题 代码块: import json friends={"name": ...

  7. spring mvc返回json格式和json字符串

    首先有必要说一下,json和json字符串是不一样的,后者是一个字符串.而json是一个对象 当然如果调用位置是后台程序这几乎没有区别,因为在后台,无论什么格式数据,都是从响应流中读取字符串. 但是在 ...

  8. JSON格式字符串作为存储过程参数解析

    1.新建可编程性的表值函数(SQLSERVER) USE [xxxx] GO /****** Object: UserDefinedFunction [dbo].[parseJSON] Script ...

  9. 通过jquery的serializearray处理表单数据成json格式,并提交到后台处理

    var params = $("#myform").serializeArray(); var values = {}; for (var item in params) { va ...

随机推荐

  1. spring boot 与 filter

    spring boot 里面用拦截器好像比用过滤器多一些. 在过滤器中, 并不能获取到action的相关信息, 会造成很多的麻烦和功能欠缺. 那, 这里就用过滤器做一个小栗子, 实际使用过程中, 不会 ...

  2. kafka主题管理

    若代理设置了 auto.create.topics.enable=true,这样还未创建topic就往kafka发送消息时, 会自动创建一个 ${num.partitions}个分区和{default ...

  3. java监听器、定时器的使用

    1.监听器 在web.xml配置 <!-- 时间任务 --> <listener> <listener-class> com.hk.common.timer.Tim ...

  4. oc for in遍历

    在oc中用for in遍历可变数组时,不能修改删除新增元素,因为for in遍历是枚举遍历,在遍历的过程中不能修改容器里的值. NSMutableArray *arr=[NSMutableArray ...

  5. 关于使用$.ajax调用ashx文件和$.post调用ashx使用中遇到的问题

    同样返回 int i = 1; string strJson = "{\"result\":" + i + "}"; context.Res ...

  6. 【C#设计模式-抽象工厂模式】

    一.抽象工厂模式的定义: 为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类. 二.抽象工厂模式的结构: 抽象工厂模式是所有形态的工厂模式中最为抽象和最具一般性的一种形态.抽象工厂模 ...

  7. JS DOM 操作 项目总结 【超链接】【数列】【span】

      超链接   每次定义链接样式时务必确认定义的顺序,link--visited--hover-active,也就是我们常说到的LoVe HAte原则(大写字母就是它们的首字母). “爱恨原则”(Lo ...

  8. 自己写一个java的mvc框架吧(四)

    自己写一个mvc框架吧(四) 写一个请求的入口,以及初始化框架 上一章写了获取方法的入参,并根据入参的参数类型进行数据转换.这时候,我们已经具备了通过反射调用方法的一切必要条件.现在我们缺少一个htt ...

  9. Elasticsearch Query DSL 整理总结(二)—— 要搞懂 Match Query,看这篇就够了

    目录 引言 构建示例 match operator 参数 analyzer lenient 参数 Fuzziness fuzzniess 参数 什么是模糊搜索? Levenshtein Edit Di ...

  10. 理解Java序列化

    前言 Java对象是在JVM中产生的,若要将其进行传输或保存到硬盘,就要将对象转换为可传输的文件流.而目前Java对象的转换方式有: 利用Java的序列化功能序列成字节(字节流),一般是需要加密传输时 ...