Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Reading back the objects Stored in String format?

$
0
0

Hi,

I have an object to be passed as string and to be read back as the object. [May not be clear with statement] But the problem is as follows;

$obj = @ {

a = 10

b = 20

}

$str_obj = <# String format of $obj#>

Now I want to execute some logic in a different env; Using IEX to run some logic on the above object.

How to convert this object to string and read it back as object of the same type?

P.S:

IEX(new-object system.io.streamreader('$path')).ReadToEnd(); test $str_obj

Thanks.


Komal.


Alternative to Windows Explorer in Server Core Windows Server 2012 R2

$
0
0

We are experimenting with Server Core for Windows Server 2012 R2. One of the big benefits of Server Core is a smaller attack surface. However, one of the downsides is the absence of Windows Explorer. Our tightly locked down environment sometimes prevents the use of the Admin shares, i.e., C$, D$, etc.

Although much of the GUI is not present in Server Core, the Operating System seems to be able to display some GUI applets, for example, Notepad, Task Manager, etc. Is there an alternative to Windows Explorer for Server Core? Maybe a PowerShell script? Something Open Source?

Search_AD_Local_Admin_Email.ps1 is not working

$
0
0

Hi everyone,

The following script is not working with PowerShell 2.0 or 4.0 (Win2008R2 or Win2012R2), can someone help me out? Thanks.

https://gallery.technet.microsoft.com/scriptcenter/Search-AD-Collect-Local-9952be71

the error what I got is below:

Search_AD : The term 'Search_AD' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At D:\Scripts\Get-LocalGroupAllMembers\Search_AD_Local_Admin_Email.ps1:13
char:1
+ Search_AD
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Search_AD:String) [], CommandNo
   tFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Search_LAdmin : The term 'Search_LAdmin' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At D:\Scripts\Get-LocalGroupAllMembers\Search_AD_Local_Admin_Email.ps1:14
char:1
+ Search_LAdmin
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Search_LAdmin:String) [], Comma
   ndNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Send_Email : The term 'Send_Email' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At D:\Scripts\Get-LocalGroupAllMembers\Search_AD_Local_Admin_Email.ps1:15
char:1
+ Send_Email
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Send_Email:String) [], CommandN
   otFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

need script for copy some folders to local

$
0
0

hello guys

i need script powershell or vbs to copy some folders on fileserver to my pc

and i need set date and genration report to success or fail

Best Regards

wait for suggests


no comment

Cannot bind argument to parameter 'Path' because it is null

$
0
0

Hi,

This is an issue with power shell when i am executing an powershell script from the PS window, the folder where the script has access rights to everyone

Current error - Cannot bind argument to parameter 'Path' because it is null

If you can help me decipher and tune the script it would do great. I have to say that this is an open source script on the web.

------------------------------

                                    

$XYZDatabase= "F:\Indexfragmentation\XYZ Database.htm" 
$serverlist = "F:\Indexfragmentation\XYZ.txt"
$QueryTimeout = 0

New-Item -ItemType file $XYZDatabase-Force

function Invoke-Sqlcmd2 ($server,$database,$query)
{
$conn=new-object System.Data.SqlClient.SQLConnection
$conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $Server,$Database
$conn.Open()
$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout=$QueryTimeout
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$conn.Close()
$ds.Tables[0]
}


Function writeHtmlHeader  
{  
param($fileName)  
$date = ( Get-Date ).ToString('yyyy/MM/dd - hh:mm')
Add-Content $fileName "<html>" 
Add-Content $fileName "<head>" 
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>" 
Add-Content $fileName '<title>XYZ Database Database Fragmentation</title>' 
add-content $fileName '<STYLE TYPE="text/css">' 
add-content $fileName  "<!--" 
add-content $fileName  "td {" 
add-content $fileName  "font-family: Tahoma;" 
add-content $fileName  "font-size: 11px;" 
add-content $fileName  "border-" 
add-content $fileName  "border-right: 1px solid #999999;" 
add-content $fileName  "border-bottom: 1px solid #999999;" 
add-content $fileName  "border-" 
add-content $fileName  "padding-" 
add-content $fileName  "padding-right: 0px;" 
add-content $fileName  "padding-bottom: 0px;" 
add-content $fileName  "padding-" 
add-content $fileName  "}" 
add-content $fileName  "body {" 
add-content $fileName  "margin-" 
add-content $fileName  "margin-" 
add-content $fileName  "margin-right: 0px;" 
add-content $fileName  "margin-bottom: 10px;" 
add-content $fileName  "" 
add-content $fileName  "table {" 
add-content $fileName  "border: thin solid #000000;" 
add-content $fileName  "}" 
add-content $fileName  "-->" 
add-content $fileName  "</style>" 
Add-Content $fileName "</head>" 
Add-Content $fileName "<body>" 
add-content $fileName  "<table width='100%'>" 
add-content $fileName  "<tr bgcolor='#CCCCCC'>" 
add-content $fileName  "<td colspan='7' height='25' align='center'>" 
add-content $fileName  "<font face='tahoma' color='#003399' size='4'><strong>XYZ Database Database Fragmentation - $date</strong></font>" 
add-content $fileName  "</td>" 
add-content $fileName  "</tr>" 
add-content $fileName  "</table>" 
}  

Function writeTableHeader  
{  

param($fileName)  
Add-Content $fileName "<tr bgcolor=#CCCCCC>" 
Add-Content $fileName "<td width='20%' align='center'>Server Name</td>"
Add-Content $fileName "<td width='20%' align='center'>Database Name</td>"
Add-Content $fileName "<td width='20%' align='center'>Table Name</td>"
Add-Content $fileName "<td width='20%' align='center'>Index Name</td>"
Add-Content $fileName "<td width='20%' align='center'>Average Fragmentation</td>"
Add-Content $fileName "<td width='20%' align='center'>Page Count</td>"
Add-Content $fileName "</tr>" 
}  

Function writeHtmlFooter  
{  
param($fileName)  
Add-Content $fileName "</body>" 
Add-Content $fileName "</html>" 
}  


Function sendEmail  
{ param($from,$to,$subject,$smtphost,$htmlFileName)  
$body = Get-Content $htmlFileName 
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost 
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
$msg.isBodyhtml = $true 
$smtp.send($msg)  
}


Function writeServiceInfo  
{  
param($fileName,$machinename,$dbname,$tbname,$ixname,$dbfrg,$dbpc)
Add-Content $filename "<tr>" 
Add-Content $filename "<td>$machineName</td>" 
Add-Content $filename "<td align=center>$dbname</td>"
Add-Content $filename "<td align=center>$tbname</td>"
Add-Content $filename "<td align=center>$ixname</td>"
$frg = [Math]::Round($dbfrg,2)
If ($frg -gt "30"){
Add-Content $filename "<td bgcolor='#FF0000' align=center>$frg</td>"}
else {
  Add-Content $filename "<td bgcolor='#387C44' align=center>$frg</td>" }

If ($dbpc -gt "1000"){
Add-Content $filename "<td bgcolor='#FF0000' align=center>$dbpc</td>"}
else {
  Add-Content $filename "<td bgcolor='#387C44' align=center>$dbpc</td>" }

Add-Content $filename "</tr>"
}

# Load SMO assembly, and if we're running SQL 2008 DLLs load the SMOExtended and SQLWMIManagement libraries
$v = [System.Reflection.Assembly]::LoadWithPartialName( 'Microsoft.SqlServer.SMO')
if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') {
  [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | out-null
  [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SQLWMIManagement') | out-null
  }

# Handle any errors that occur
Trap {
  # Handle the error
  $err = $_.Exception
  write-host $err.Message
  while( $err.InnerException ) {
$err = $err.InnerException
write-output $err.Message
};
  # End the script.
  break
  }


writeHtmlHeader $XYZ Database

foreach ($server in Get-Content $serverlist)
{
Add-Content $XYZDatabase"<table width='100%'><tbody>" 
Add-Content $XYZDatabase"<tr bgcolor='#CCCCCC'>" 
Add-Content $XYZDatabase"<td width='100%' align='center' colSpan=6><font face='tahoma' color='#003399' size='2'><strong> $server </strong></font></td>" 
Add-Content $XYZDatabase"</tr>" 
writeTableHeader $XYZ Database

# Connect to the specified instance
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $server

# Get the databases for the instance, and iterate through them
$dbs = $s.Databases
foreach ($db in $dbs) {
 # Check to make sure the database is not a system database, and is accessible
 if ($db.IsSystemObject -ne $True -and $db.IsAccessible -eq $True -and $db.Name -like 'XYZ') {
   # Store the database name for reporting
   $dbname = $db.Name
   $dbid = [string]$db.ID

   $tbs = $db.Tables
   foreach ($tb in $tbs) {
     # Store the table name for reporting
     $tbname = $tb.Name
     $tbid = [string]$tb.ID

   $ixs = $tb.Indexes
     foreach ($ix in $ixs) {
       # We don't want to process XML indexes
if ($ix.IsXmlIndex -eq $False) {
         # Store the index name for reporting
         $ixname = $ix.Name
         $ixid = [string]$ix.ID

              # Get the Fragmentation and page count information 
          $q = @"
 select avg_fragmentation_in_percent, page_count
 from sys.dm_db_index_physical_stats($dbid, $tbid, $ixid, NULL, NULL)
"@ 
          $res = invoke-sqlcmd2 $server $dbname $q
          $frval = $res.avg_fragmentation_in_percent
          $pgcnt = $res.page_count  
          writeServiceinfo $XYZDatabase$server $dbname $tbname $ixname $frval $pgcnt 
        }
        }
      }

    }
  }
Add-Content $XYZDatabase"</table>" 
}

Writehtmlfooter $XYZ Database
$date = ( Get-Date ).ToString('yyyy/MM/dd - hh:mm')
sendEmail x.abc.com "x.y@abc.com" "XYZ Database Database Fragmentation Level" x.x.com $XYZ Database

-----------------------------------

Get-ADUser used in function to search by givenname and surname - Get-ADUser : Invalid type 'System.Object[]'

$
0
0

Can someone tell me why this works -

$User = Get-ADUser -Filter {(surname -eq $Last) -and (givenname -eq $First)} | Format-List *
$User

DistinguishedName  : CN=smith,OU=Users,DC=ad,DC=somewhere,DC=com
Enabled            : True
GivenName          : John
Name               : smith
ObjectClass        : user
ObjectGUID         : xxxxxxxx-xxxx-xxxxxxxx-xxxxxxxxxx
SamAccountName     : jsmith
SID                : x-x-x-xx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxx
Surname            : Smith
UserPrincipalName  : john.smith@somewhere.com
PropertyNames      : {DistinguishedName, Enabled, GivenName, Name...}
AddedProperties    : {}
RemovedProperties  : {}
ModifiedProperties : {}
PropertyCount      : 10

but, this does not? -

$User = ""
Function UserSearch($LastName,$FirstName) {
    $User = Get-ADUser -Filter {(surname -eq $LastName) -and (givenname -eq $FirstName)} | Format-List *
    Return $User
}

$Last = 'Smith'
$First = 'John'

UserSearch($Last,$First)
$User

Get-ADUser : Invalid type 'System.Object[]'.
Parameter name: sn
At line:3 char:13
+     $User = Get-ADUser -Filter {(surname -eq $LastName) -and (givenna ...+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Trying to use Add-Computer -ComputerName (Get-Content Computers.txt)

$
0
0

I've been trying to test out joining computers to a domain using the command below.  My reference for this is from Microsoft, here.   

Add-Computer -ComputerName (Get-Content Computers.txt) -Domain IMG.local -Credential IMG\Administrator -Options Win9xUpgrade -Restart

I have "Computers.txt" created with one test computer in it.  This text file is located in the same folder where the script is.  

Below is my error when running.  Any suggestions?

Add-Computer : A parameter cannot be found that matches parameter name 'ComputerName'.
At \\imaging\d$\Support\Domain Migration\Join_Domain.ps1:1 char:27+ Add-Computer -ComputerName <<<<  (Get-Content Computers.txt) -Domain IMG.local -Credential IMG\Administra
tor -Options Win9xUpgrade -Restart+ CategoryInfo          : InvalidArgument: (:) [Add-Computer], ParameterBindingException+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.AddComputerCommand

Count and AD group membership

$
0
0

If I use Count to return the number of members in a group it works fine, but only if the count is greater than 1, e.g.

(Get-ADGroupMember -Identity "Count Test").count

If the group "Count Test" contains 0 or 1 members no output is returned.  If the group contains 2 or more members the count (integer) is returned as expected. 

Any thoughts on why it is doing this?  I'd also be happy for alternative.  I just need to be able to determine the count.


Alexei

Why do I get an exception calling 'ReadKey'?

$
0
0

Hello,

I run the following code in my script.  What displays is 'Press any key to continue' which is the intent, but then the following error occurs without a key being pressed and the script proceeds.  I dont understand the error. Any insight as to why I see this error?

write-Host "Press any key to continue.."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Exception calling "ReadKey" with "1" argument(s): "The method or operation is not
implemented."
At C:\adtest.ps1:247 char:1+ $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : NotImplementedException


Thanks for your help! SdeDot

Pass a Where Clause as a Parameter

$
0
0

Greetings,

I'd like to pass a where clause as a parameter.  How do I do this?

Something like this:

$whereClause = "$_.Name -like 'a*'"

$aFiles = $aFolders.Files | where { $whereClause }

Thank you!

O365 Active Sync

$
0
0
How to check user active sync is enable or not in o365.

Satish Chaturvedi Mob-9990806001

o365

$
0
0
how to connect o365 step by step guide

Satish Chaturvedi Mob-9990806001

Invoke-ProcessASDatabase

$
0
0

I am attempting to process an Analysis Services tabular model via PowerShell... well, we've tried other methods but none of them worked so this is getting to our last resort and as with everything Microsoft, not going well.

My attempt is to follow this guide

https://technet.microsoft.com/en-us/library/hh213141(v=sql.130).aspx

I have installed v16.5.3 of Management Studio (Help->About shows v13.0.16106.4) but when doing the "Get-Command -Module sqlascmdlets", I don't get the list stated (in particular, I don't have Invoke-ASProcessDatabase), what I do have is

 Name                                               ModuleName
 ----                                               ----------
 Add-RoleMember                                     sqlascmdlets
 Backup-ASDatabase                                  sqlascmdlets
 Invoke-ASCmd                                       sqlascmdlets
 Invoke-ProcessCube                                 sqlascmdlets
 Invoke-ProcessDimension                            sqlascmdlets
 Invoke-ProcessPartition                            sqlascmdlets
 Merge-Partition                                    sqlascmdlets
 New-RestoreFolder                                  sqlascmdlets
 New-RestoreLocation                                sqlascmdlets
 Remove-RoleMember                                  sqlascmdlets
 Restore-ASDatabase                                 sqlascmdlets

Where does Invoke-ProcessASDatabase come from?


SOLVED: read value from xml and create variables for them.

$
0
0
 $xml = @"<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><S N="Manufacturer">Igor Pavlov</S><S N="MSI_File">7z1604-x64.msi</S><S N="ProductCode">{23170F69-40C1-2702-1604-000001000000}</S><S N="ProductVersion">16.04.00.0</S><S N="UpgradeCode">{23170F69-40C1-2702-0000-000004000000}</S><S N="ProductName">7-Zip 16.04 (x64 edition)</S><S N="MST_File">none</S></MS></Obj></Objs>"@

[xml]$XmlDocument = $xml

$value = $XmlDocument.Objs.obj.ms.S

$value
    

Above code give me this output:

N              #text
-              -----
Manufacturer   Igor Pavlov
MSI_File       7z1604-x64.msi
ProductCode    {23170F69-40C1-2702-1604-000001000000}
ProductVersion 16.04.00.0
UpgradeCode    {23170F69-40C1-2702-0000-000004000000}
ProductName    7-Zip 16.04 (x64 edition)
MST_File       none             

I want to assign the value to the right to the a variable so:

$Manufacturer will store the value "Igor Pavlov"

$MSI_File will store the value "7z1604-x64.msi" and so on.

is there a simple way to do this... have google the for sample to figure out how to handle xml in powershell. But no luck


#LnQ¯\_(ツ)_/¯


Exporting Specific Users Info From Get-ADUser

$
0
0

I am attempting to look at every single user in my AD and am able to pull every user and push it to a CSV with SamAccountName, Enabled, and msds-resultantPSO properties. However, this creates almost 3000 lines for my 800+ users. All I really want is to see is who doesn't have it enabled which can be determined by the Enabled property being "False" or the msds-resultantPSO property being null.

Here is the script to do that:

Get-ADUser -filter * -property msds-resultantPSO | fl SamAccountName,Enabled,msds-resultantPSO

Output in CSV looks like this:

SamAccountName: User

Enabled: False (or true, depending if they have one active)

msds-ResultantPSO: (blank) (or the name of the policy)

This gets me every user and that data. I only want users with "Enabled" as "False" or "msds-resultantPSO" as null. 

Any help?


intermittent : The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program.

$
0
0

I have developed a batch harness whereby all scheduled tasks (W2012) invoke a common powershell script that acts as a wrapper to all our housekeeping jobs.

The first step in the wrapper is to create a Transcript file using following code

if ($Host.name -ne "Windows PowerShell ISE Host") # Transcript does not work within ISE
{
$timestamp = (get-date -format "yyyy-MM-dd-HH-mm-ss.fff")
$path = "c:\corp\$timestamp" + "_$pid.txt"
Start-Transcript -path $path -append
}

As expected the folder contains files with timestamp & pid in name

08/08/2013  11:00 AM            14,388 2013-08-08-11-00-01.158_1620.txt
08/08/2013  11:00 AM            12,506 2013-08-08-11-00-01.485_936.txt
08/08/2013  11:00 AM            12,994 2013-08-08-11-00-01.735_9328.txt
08/08/2013  11:00 AM            12,024 2013-08-08-11-00-01.766_8624.txt
08/08/2013  11:00 AM            13,902 2013-08-08-11-00-01.860_1756.txt
08/08/2013  11:01 AM            15,142 2013-08-08-11-01-31.392_10120.txt
08/08/2013  05:00 AM            14,982 _1692.txt

However note the last file, it has a zero length date time value in the name

The error recorded by PowerShell is

get-date : The term 'get-date' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Corp\Powershell\DMPRun-ScheduledTask.ps1:171 char:18
+    $timestamp = (get-date -format "yyyy-MM-dd-HH-mm-ss.fff")
+                  ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (get-date:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

IE get-date has failed and returned a zero length field as the timestamp

Can anyone think of a good reason why get-date would fail intermittently?

Do I have to code defensively for base Powershell functions?

Bizarre issue with Copy-Item making a file from folder name

$
0
0

Goodness me, I didn't think the act of copying a file was the part of the script I would be debugging!

I'm having a really bizarre issue with Copy-Item. Basically, I have a config file I need to move into Program Files.

Here's my command:

Copy-Item -Path "C:\install\app.exe.config" -Destination "$ProgamFiles\MyApp\bin"


$ProgamFiles will expand in C:\Program Files or C:\Program Files (x86) depending on 32 or 64-bit Windows. However, in both scripts, or simply writing this in Powershell as a solo command, with either using $ProgamFiles or just full out typing C:\Program Files (x86), app.exe.config becomes a file called bin in the MyApp folder. I must admit I have not tested if I have this issue on 32-bit Windows where the path would be C:\Program Files as right now this will be run on Windows 64-bit 99% of the time.

An example of the dir command looks like this after a copy Item in the MyApp folder:

<DIR> .<DIR> ..<DIR>        bin
          16 bin<DIR>        Assets

And the file called bin has the contents of my old app.exe.config

So, okay, it wants to make a file with the last thing in the Destination string, so I try this:

Copy-Item -Path "C:\install\app.exe.config" -Destination "$ProgamFiles\MyApp\bin\app.exe.config"

But I get the filename, Directory Name, or volume name syntax is incorrect.

So yeah, I'm really scratching my head on this one. I thought maybe the brackets in (x86) might be throwing it off, but escaping them with ` didn't help. I got the exact same outcome. And I have a Test-Path command that looks for something in Program Files (x86) without issue. It also can't be a permissions issue, because I AM getting a file written to the destination, and the PowerShell is running as administrator. Any thoughts as to why I'm getting this output instead of what I really want?


network path was not found when use invoke

$
0
0

Prompt error of "Exception calling "Invoke" with "2" argument(s): "The network path was not found" " when I'm try to change password of administrator in remote server by below command at 1st time, but works if I triggered in 2nd time.

$admin=[ADSI]("WinNT://" + $strComputer + "/administrator,user")
$admin.psbase.invoke("SetPassword",$Password)

I tried add one more command line test-connetion or start-sleep but still the same.

Any solutions would be much helpful, thanks.

Cheers

Joe

Get-WindowsFeature hyper-v or other feature - I would like to ADD the name from the computer to the result

$
0
0

Hello,

the script shows the result of the servers that have the Hyper-v Feature installed and ignore all the others servers that don't have it, but the problem is that, when you get this from a .txt file you don't know which servers have the rule installed. My goal is to add the server Name to the result.

$HypervHost = Get-Content "C:\hyper-vservers.txt"

 foreach ($Hyper in $HypervHost) {Get-WindowsFeature hyper-v -ComputerName $Hyper -ErrorAction SilentlyContinue } 

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] Hyper-V                                             Hyper-V                        Installed
[X] Hyper-V                                             Hyper-V                        Installed
[X] Hyper-V                                             Hyper-V                        Installed
[X] Hyper-V                                             Hyper-V                        Installed

Thanks,

MN


Convert curl script to powershell

$
0
0

I want to convert a curl script to powershell. Could you please help me out in this?

Here is the curl script that needs to be converted

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{"computers": ["server123"
  ],"content": [
    {"Name": "Execute-BlankAction","Parameters": {"parameterName": "string"
      }
    }
  ],"uid": "abcd","description": "string","email": "string"
}' 'https://xyz.com/api/v1/job/'

Here is the powershell script i used. I need computers, Name and UID in the powershell script. I believe i have screwed up something in the body section of the script due to which it is not getting the computer information.

$cred=Get-Credential

$data = @{
    computers='server123'
Name='execute-BlankAction'
    uid= 'abcd'
}

$body=$data|ConvertTo-Json
$body
Invoke-restmethod -Uri 'https://xyz.com/api/v1/job/' -Method Post -Body $body -Credential $cred -ContentType 'application/json' 

but i am getting message as 

status_text : Error: No computers[] were entered. Must enter at least one
error_text  : Can NOT execute job
status_code : 200
status      : Failed
rc          : 1


Viewing all 21975 articles
Browse latest View live