Powershell: How Can I get the random property of get-service cmdlet? - properties

I have:
$services = get-service | get-random -count 5 | Select-Object -Property DisplayName, Status, *HERE I WANT 2 RANDOM PROPERTIES*
I created a list of random properties:
$randomPropertyName = get-service | get-member | Where-Object memberType -eq property | get-random -count 2 | Select-Object name
and i cannot convert it from object.array to string, I tried:
[string]$random1 = $randomPropertyName[0] | ft -hidetableheaders

Related

Get variable from tenant in Octopus

Is there any way to get a variable from tenant in Octopus server?
I already extracting variable from projects, using code below, but this method is not working for tenants:
Import-Module "C:\Program Files\WindowsPowerShell\Modules\Octopus-Cmdlets\0.4.4\Octopus-Cmdlets.psd1"
connect-octoserver http://octohost.cloudapp.azure.com:8082 API-12345678901234567890
$raw = (Get-OctoVariable someproject somevariable | Where-Object { $_.Environment -eq "DEV" } )
$jsonfile = "c:\dataapi.json"
$raw.Value | ConvertFrom-Json | ConvertTo-Json | Out-File $jsonfile -Encoding UTF8
$data = Get-Content $jsonfile -Encoding UTF8 | ConvertFrom-Json
$data | ConvertTo-Json | Set-Content $jsonfile -Encoding UTF8
There is at least the following way to get a variable from a tenant in Octopus Deploy. I got this working with making OctopusClient.dll calls.
Add-Type -Path $OctopusClientDll #this should point to the dll
$Endpoint = New-Object Octopus.Client.OctopusServerEndpoint $octopusURI, $apiKey
$Repository = New-Object Octopus.Client.OctopusRepository $Endpoint
$TenantEditor = $Repository.Tenants.CreateOrModify($TenantName)
$Vars = $TenantEditor.Variables.Instance.LibraryVariables
$VarSet = $Vars[$COMMON_TENANT_VARSET_ID] # you need to know this
$VarTemplate = $VarSet.Templates | Where-Object -Property Name -eq "Tenant.VariableName"
$VariableValue = $VarSet.Variables[$varTemplate.Id].Value

Dynamic server value in powershell

I am using below query to get the server details,
$intFreeSpace = Get-WmiObject -Class win32_logicalDisk -ComputerName Server1,server2 | Select-Object SystemName, deviceid, freespace, size
Now, instead of hard coded value I tried to supply server value from a variable like below
$serverlist = "server1,server2"
$intFreeSpace = Get-WmiObject -Class win32_logicalDisk -ComputerName $serverlist | Select-Object SystemName, deviceid, freespace, size
but this isn't working, any solution?
Edit:
ServerList = #("Server1") #Initialization with dummy value to insure that variable will be an array
if($row[0] -eq "ServerList"){
$ServerList= $row[1]
}
WRITE-HOST $ServerList
Output: Server1,Server2
It is working fine when my column value is Server1.
Pass in an array, instead! Otherwise, you make an attempt on 'one' computer called "server1,server2".
$serverlist = #("server1","server2")
$intFreeSpace = Get-WmiObject -Class win32_logicalDisk -ComputerName $serverlist | Select-Object SystemName, deviceid, freespace, size
EDIT: Bill is right, you'll need to turn your string of servers into an array. Since the result is comma delimited, you can -split on the comma. This leaves you with an array.
$serverlist = $serverlist -split ','
$intFreeSpace = Get-WmiObject -Class win32_logicalDisk -ComputerName $serverlist | Select-Object SystemName, deviceid, freespace, size

How to add hardcoded value to WMI output in Powershell

I am new to powershell, i am trying to retrieve the SQL Services details using WMI object. My code is as follows:
$InputFile = Import-Csv "C:\input\Servers.csv" | %{ $_.Instance = $_.Instance -replace "\\.*?$" ; $_}
Write-Output "SQL Services details for Server:" | Out-File C:\output\SQLCHECK.STOPPED.LOG
Write-Output "********************************" | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
foreach($Servers in $Inputfile)
{
Write-Output $Servers|ft -AutoSize | Out-File C:\output\SQLCHECK.STOPPED.LOG
$Servicesstate=Get-WmiObject win32_service -ComputerName $Servers.instance | Select Name, Startmode, State | Where-Object `
{$_.name -like "*SQL*" -and $_.Startmode -match "Auto" -and $_.state -match "Stopped"} | ft -auto
if (!$Servicesstate )
{
Write-Host "No Services in STOP state"
Write-Output "No Services in STOPPED state" | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
}
Else
{
echo ($Servicesstate )
Write-Output ($Servicesstate) | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
}
}
My Output will come something like this:
Instance Name:
ABCDEFGH
Name Startmode State
SQLdmCollectionService$Default Auto Stopped
SQLdmManagementService$Default Auto Stopped
SQLdmPredictiveAnalyticsService$Default Auto Stopped
My question is, how to add a additional column to the output and add custom text as values.
I want to add remarks column and display failed if any services are stopped.
Name Startmode State Remarks
SQLdmCollectionService$Default Auto Stopped Failed
SQLdmManagementService$Default Auto Stopped Failed
SQLdmPredictiveAnalyticsService$Default Auto Stopped Failed
Your columns are defined by what you put in Select-Object, as you only have Name, Startmode and State those will be the columns.
Change
Select Name,Startmode,State
To
Select-Object Name,Startmode,State,Remark
By adding another property called Remarks you will effectively add another column to your output and you can change the value of Remark by calling the property like so
$Servicestate.Remark = 'Failed'
So you're final code might look something like this
$InputFile = Import-Csv "C:\input\Servers.csv" | %{ $_.Instance = $_.Instance -replace "\\.*?$" ; $_}
Write-Output "SQL Services details for Server:" | Out-File C:\output\SQLCHECK.STOPPED.LOG
Write-Output "********************************" | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
foreach($Servers in $Inputfile)
{
Write-Output $Servers|ft -AutoSize | Out-File C:\output\SQLCHECK.STOPPED.LOG
$Servicesstate=Get-WmiObject win32_service -ComputerName $Servers.instance | Select Name, Startmode, State | Where-Object `
{$_.name -like "*SQL*" -and $_.Startmode -match "Auto" -and $_.state -match "Stopped"} | ft -auto
if (!$Servicesstate )
{
# Edit the new column before you output
$Servicestate.Remark = 'Failed'
Write-Host "No Services in STOP state"
Write-Output "No Services in STOPPED state" | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
}
Else
{
# Edit the new column before you output
$Servicestate.Remark = 'Success'
echo ($Servicesstate )
Write-Output ($Servicesstate) | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
}
}
When assigning your values to $servicestate you can pipe to a Select command and create an extra value with a hashtable. Check out this slightly modified version of your script, paying close attention to line 9:
$InputFile = Import-Csv "C:\input\Servers.csv" | %{ $_.Instance = $_.Instance -replace "\\.*?$" ; $_}
Write-Output "SQL Services details for Server:" | Out-File C:\output\SQLCHECK.STOPPED.LOG
Write-Output "********************************" | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
foreach($Servers in $Inputfile)
{
Write-Output $Servers|ft -AutoSize | Out-File C:\output\SQLCHECK.STOPPED.LOG
$Servicesstate=Get-WmiObject win32_service -ComputerName $Servers.instance | Select Name, Startmode, State |
Where{$_.name -like "*SQL*" -and $_.Startmode -match "Auto" -and $_.state -match "Stopped"}|Select Name,Startmode,State,#{l='Remarks';e={if($_.State -eq "Stopped"){"Failed"}}}
if (!$Servicesstate )
{
Write-Host "No Services in STOP state"
Write-Output "No Services in STOPPED state" | Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
}
Else
{
echo ($Servicesstate|ft -AutoSize )
Write-Output ($Servicesstate) |FT -auto| Out-File C:\output\SQLCHECK.STOPPED.LOG -Append
}
}

Pompt if no input entered

If I just press enter without entering any variable.. it will spit out errors. What can I add to make it just repompt again?
mode con: cols=35 lines=5
while (1) {
$tag1 = Read-Host 'Enter tag # or Q to quit'
if ($tag1 -eq "Q") {
break;
}
mode con: cols=80 lines=46
cls
sc.exe \\$tag1 start RemoteRegistry;
cls
start-sleep -seconds 2
cls
$OSInfo = get-wmiobject -class win32_operatingsystem -computername $tag1;
$OSInfo | Format-Table -Property #{Name="OS Name";Expression={$_.Caption}} -AutoSize;
$OSInfo | Format-Table -Property #{Name="System Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} -AutoSize;
$OSInfo | Format-Table -Property #{Name="OS Install Date";Expression={$_.ConvertToDateTime($_.InstallDate)}} -AutoSize;
"`n"
"Current Date & Time: $(Get-Date -Format G)";
"`n"
Get-WmiObject win32_computersystem -Computer $tag1 | Format-Table -Property #{Name="Username";Expression={$_.username}} -Autosize;
Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | format-table EventID,TimeWritten,MachineName -AutoSize;
}
Couple of different ways:
$tag1 = $null
while (-not $tag1 ) {
$tag1 = Read-Host 'Enter tag # or Q to quit'
if ($tag1 -eq "Q") {
return;
}
}
mode con: cols=80 lines=46
cls
sc.exe \\$tag1 start RemoteRegistry;
cls
start-sleep -seconds 2
cls
$OSInfo = get-wmiobject -class win32_operatingsystem -computername $tag1;
$OSInfo | Format-Table -Property #{Name="OS Name";Expression={$_.Caption}} -AutoSize;
$OSInfo | Format-Table -Property #{Name="System Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}} -AutoSize;
$OSInfo | Format-Table -Property #{Name="OS Install Date";Expression={$_.ConvertToDateTime($_.InstallDate)}} -AutoSize;
"`n"
"Current Date & Time: $(Get-Date -Format G)";
"`n"
Get-WmiObject win32_computersystem -Computer $tag1 | Format-Table -Property #{Name="Username";Expression={$_.username}} -Autosize;
Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | format-table EventID,TimeWritten,MachineName -AutoSize;
Or:
$GetTag = {
Switch (Read-Host 'Enter tag # or Q to quit')
{
'Q' {Return}
'' {.$GetTag}
default {$_}
}
}
$tag = &$GetTag
Just clear the variable and then loop until it is set.
$tag1 = ""
while (-not ($tag1)) {
$tag1 = Read-Host 'Enter tag # or Q to quit'
}

Read var directly from csv

Is it possible to read a variable directly by loading a csv?
My csv looks like this:
Var,Path
$SrcHost,\\computer
Is there a possibility to import-csv and put the path into the var?
import-csv test3.csv | foreach-object {
iex "$($_.var) = ""$($_.path)"""
}
You can also use new-variable (nv):
import-csv csvfile.csv | % { nv -name ($_.var) -value ($_.path) }
However to make this work you have to:
remove the $ from the source csv
or, trim $ as described by the comments below
or, select your variable as ${$srchost}
How bout this:
Get-Content -Path test.csv | Select-Object -Skip 1 | ForEach-Object { $_.Replace(",", "=`"") +
"`"" } | Invoke-Expression