how to use variable out of invoke-command in powershell? - powershell

I have below Invoke-command code, the script using hponcfg.exe file on remote server to get ILO configuration. few servers having issue with power capping and error returned by hponcfg.exe as
"Message = 0x0089 Power capping information is not available at this time, try again later."
My question is: I want to capture this error if generated by hponcfg inside invoke-command scriptblock and use it out of scriptblock.
$CurrentDir = (Split-Path $invocation.MyCommand.Path).ToLower()
$CurrentDir
$Credential = get-credential -message "Please supply SA account details."
$servers = gc .\servers.txt
#$Global:ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$date = (get-date).ToString("yyyyMMdd_HHmm")
$ILOContent = ".\ILOConfigData_$date.csv"
New-Item -path $ILOContent -type file -Force | out-null
Add-Content -Path $ILOContent -Value "ILO_Name,Model,ILOFIrmware,ILODevice,ILOFWDate,ILO_Domain,Network_Details,ILO_TimeZone,Directory_Users,LDAP_Directory_Authentication,Directory_Groups,SNMP_Settings,Directory_Server_Address"
Foreach($server in $servers){
if (Test-Connection -ComputerName $server -Quiet)
{
#$Frompath = ".\ILO_Prerequisite\"
#$To_Path = "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
$tmp="Drv_$server"
new-psdrive $tmp filesystem "\\$server\C$" -cred $cred|Out-Null
$Model = (Get-WmiObject -ComputerName $server -Class:Win32_ComputerSystem).model
Write-Host "Validating HPE pre-requisites on server:"$server -BackgroundColor DarkGray -ForegroundColor White
if (-not(test-path("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG")))
{
Write-Host "Corrupt 'HPONCFG' folder structure found. Remediating, will take few seconds." -ForegroundColor Red
New-Item -Path ("$($tmp):\Program Files\Hewlett Packard Enterprise\") -ItemType Directory -Name HPONCFG -Force|Out-Null
$To_Path =("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG")
$From_Path = ".\ILO-PreRequisite\*"
copy-item -path $From_Path -Destination $To_Path -recurse -Force
Sleep(6)
Write-Host "'HPONCFG' folder structure remediated." -ForegroundColor Green
}
Elseif (-not(test-path("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe")))
{
$To_Path =("$($tmp):\Program Files\Hewlett Packard Enterprise\HPONCFG")
Write-Host "Corrupt 'HPONCFG' folder structure found. Remediating, will take few seconds." -ForegroundColor Red
copy-item -path $From_Path -Destination $To_Path -recurse -Force
Sleep(6)
Write-Host "'HPONCFG' folder structure remediated" -ForegroundColor Green
}
remove-psdrive -name $tmp -force
#if (-not(test-path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe"))
# {
# do copy job
# write-host "Copying files and folders from $frompath to $topath" -ForegroundColor Yellow
# copy-item -path $frompath -Destination $topath -recurse
# }
$export = Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
New-Item -Path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG" -ItemType File -Name Current_ILOConfig.xml -Force| Out-Null
Set-Location "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
$ILODataPath = Get-Location
$WantFile = "$ILODataPath\Current_ILOConfig.txt"
$FileExists = Test-Path $WantFile
If ($FileExists -eq $True) {Remove-Item $WantFile }
Sleep(2)
Write-Host "Gathering current ILO configuration for $ENV:COMPUTERNAME" -ForegroundColor Yellow
& "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
"C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" |Out-Null
Get-Content .\Current_ILOConfig.xml
}
$export|Out-File "Current_ILOConfig.txt"
Sleep(3)
$ILORAW_DATA = Get-Content .\Current_ILOConfig.txt
$ILORAW_DATA|ForEach-Object{
$_ -replace '<!-- ' `
-replace ' -->' `
-replace '<' `
-replace ' />' `
-replace '"' `
}|Set-Content .\Current_ILOConfig.txt
$ILO_DATA = Get-Content .\Current_ILOConfig.txt
Write-Host "Getting ILO DNS details"
$DNS_NAME = $ILO_DATA |Where {$_ |Select-String -Pattern " DNS_NAME VALUE"," DOMAIN_NAME VALUE"}
$ILONAME = $DNS_NAME -split "="
$ILO_Name = $ILONAME[1]
$ILO_Domain = $ILONAME[3]
Write-Host "Getting ILO Network details"
$NT = $ILO_DATA | where {$_ |Select-String -Pattern " IP_ADDRESS VALUE"," SUBNET_MASK"," GATEWAY_IP_ADDRESS"," PRIM_DNS_SERVER VALUE", " SEC_DNS_SERVER VALUE"," TER_DNS_SERVER VALUE" }
$Network = [array]$NT -join "`n"
$Network_Details = $Network.Trim()
Write-Host "Getting ILO TimeZone"
$TZ= $ILO_DATA |Where {$_ | Select-String -Pattern " TIMEZONE VALUE"}
$TimeZone =$TZ -Split "="
$ILO_TimeZone = $TimeZone[1]
Write-Host "Getting ILO Directory Server Address" # Directory_Server_Address
$DSA = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_SERVER_ADDRESS"}
$DIR_SERVERADDRESS = $DSA -Split "="
$Directory_Server_Address = $DIR_SERVERADDRESS[1]
$ILODeviceID = #()
$ILODev = $ILO_DATA|where{$_|Select-String -Pattern "Device: "}
$ILODevStr = $ILODev -split(' ')
$ILODeviceID += $ILODevStr[1..2] -as [string]
$ILODeviceID += $ILODevStr[7]
$ILODeviceID += $ILODevStr[-1]
Write-Host "Getting LDAP Directory Authentication Enabled/Disabled?"
$LDAP_DIR = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_AUTHENTICATION_ENABLED"}
$LDAP_DIR_STATUS = $LDAP_DIR -split "="
$LDAP_Directory_Authentication = $LDAP_DIR_STATUS[1]
Write-Host "Getting ILO Device detail"
$ILOFIrmware = $ILODevStr[7]
Write-Host "Getting ILO Firmware Version"
$ILODevice = $ILODevStr[1,2]
Write-Host "Getting ILO Firmware Version date"
$ILOFWDate = $ILODevStr[-1]
Write-Host "Getting SNMP Settings" #SNMP_Settings
$SNMPADDRESS = $ILO_DATA |Where {$_ | Select-String -Pattern "SNMP_ADDRESS"}
$SNMP_DATA = #()
foreach($SNMP in $SNMPADDRESS)
{
$SNMP_DATA +=($SNMP -split "VALUE=")[1]
}
$SNMP_Settings = $SNMP_DATA -join "`n"
Write-Host "Getting ILO Directory User details"
$DIR_USER = $ILO_DATA |Where {$_ | Select-String -Pattern " DIR_USER_CONTEXT"}
$User =#()
foreach($Usr in $DIR_USER)
{
$User += ($Usr -split "VALUE=")[1]
}
#$User
$Directory_Users = $User -join "`n"
#group Account details
Write-Host "Getting ILO Directory Group details"
$DIR_GRPACCT = $ILO_DATA |Where {$_ | Select-String -pattern " DIR_GRPACCT"}
$ACCTs = #()
for($a=1;$a -le 10;$a++)
{
$GroupName = "DIR_GRPACCT" + $a + "_NAME"
#$Privilege = "DIR_GRPACCT" + $a + "_PRIV"
$DIR_GRPACCT = $ILO_DATA |Where {$_ | Select-String -pattern $groupname}
foreach ($acct in $DIR_GRPACCT)
{
$ACCTS += ($acct -split "VALUE=")[1]
}
$DIR_GRPACCTS = ($ACCTS -join "`n")
}
$data = "`"$ILO_Name`",`"$Model`",`"$ILOFIrmware`",`"$ILODevice`",`"$ILOFWDate`",`"$ILO_Domain`",`"$Network_Details`",`"$ILO_TimeZone`",`"$($Directory_Users.trimend())`",`"$LDAP_Directory_Authentication`",`"$($DIR_GRPACCTS.trimend())`",`"$($SNMP_Settings.trimend())`",`"$($Directory_Server_Address.trimend())`""
$Data |Out-File -Append $ILOContent
}
else
{
write-host -ForegroundColor Red "Server $server is not reachable"
$data = "`"$server`",`"not reachable`""
$Data |Out-File -Append $ILOContent
}
}
#Clear User defined variables
Write-Host "Performing Clean-up" -ForegroundColor Yellow
#Clear-Variable -Name ILO*
Function Get-ScriptVariable ($Name = '*')
{
# these variables may exist in certain environments (like ISE, or after use of foreach)
$special = 'ps','psise','psunsupportedconsoleapplications', 'foreach', 'profile'
$ps = [PowerShell]::Create()
$null = $ps.AddScript('$null=$host;Get-Variable')
$reserved = $ps.Invoke() |
Select-Object -ExpandProperty Name
$ps.Runspace.Close()
$ps.Dispose()
Get-Variable -Scope Global |
Where-Object Name -like $Name |
Where-Object { $reserved -notcontains $_.Name } |
Where-Object { $special -notcontains $_.Name } |
Where-Object Name
}Get-ScriptVariable|Out-Null
Get-ScriptVariable |Clear-Variable ;Write-Host "Clean-up completed." -ForegroundColor Green
Write-Host "Check detailed log stored at path: "$CurrentDir -ForegroundColor Green```

You can use try-catch-finally method to get your error messages.
Hi I have modified your script invoke-command part only. Please test and use it. This script is not tested.
$export = Invoke-Command -ComputerName $server -Credential $Credential -ScriptBlock {
try {
New-Item -Path "C:\Program Files\Hewlett Packard Enterprise\HPONCFG" -ItemType File -Name Current_ILOConfig.xml -Force | Out-Null
Set-Location "C:\Program Files\Hewlett Packard Enterprise\HPONCFG"
$ILODataPath = Get-Location
$WantFile = "$ILODataPath\Current_ILOConfig.txt"
$FileExists = Test-Path $WantFile
If ($FileExists -eq $True) { Remove-Item $WantFile }
Sleep(2)
Write-Host "Gathering current ILO configuration for $ENV:COMPUTERNAME" -ForegroundColor Yellow
& "C:\Program Files\Hewlett Packard Enterprise\HPONCFG\hponcfg.exe" /a /w `
"C:\Program Files\Hewlett Packard Enterprise\HPONCFG\Current_ILOConfig.xml" | Out-Null
Get-Content .\Current_ILOConfig.xml
}
catch {
return $_
}
}
$export | Out-File "Current_ILOConfig.txt"

Related

Powershell Loop though specific json files from multiple folders and use that json file to push into Loop

$tenantID = (Get-AzureADTenantDetail).ObjectId
$mg = "/providers/Microsoft.Management/managementGroups/" + $tenantID
foreach($subfolder in Get-ChildItem -Path C:\Users\xxxx\Desktop\AzurePolicies -Depth 2 -Recurse){
Write-Host "Subfolder is " $subfolder
foreach($file in Get-ChildItem -Path $subfolder -File *.json -Recurse){
foreach($policy in $file){
$displayname = (Get-Content $file -Raw | ConvertFrom-Json).properties.displayName
Write-Host "Display name is" $displayname
$policyname = (Get-Content $policy -Raw | ConvertFrom-Json).properties.name
Write-Host "Policy name is" $policyname
foreach ($item in $policy) {
function DefinePolicies {
New-AzPolicyDefinition -Name $policyname -DisplayName $displayname -Policy $policy -ManagementGroupName $tenantID
Start-Sleep -Seconds 2
}
DefinePolicies
function AssignPolicies {
$policy = Get-AzPolicyDefinition -Name $policyname -ManagementGroupName $tenantID
New-AzPolicyAssignment -Name $policyname -PolicyDefinition $policy -Scope $mg
Start-Sleep -Seconds 2
}
AssignPolicies
}
}
}
}
My Files are organized as Azurepolicies/Keyvaults/Somepolicy/azurepolicy.json

Why is my if statement not being read properly?

I have a script that backs up a user profile from the local, or remote machine and places it onto a share: $Global:Shared_BackupPath = "\\server\share\". I've been tweaking it a little more and just ended up making some variables into Global variables (not sure if this is the issue - dont see why it would be).
This is the condition:
if(-not (Get-EventSubscriber)){
I tried changing it to -eq $null to see if it would make any difference, but it didn't.
Its just not analyzing the condition properly and goes on to display my message box before all Jobs are done: it's "supposed" to wait till there's no more events and then display the message box:
Register-ObjectEvent -InputObject $job -EventName StateChanged -Action {
#Start-Sleep -Milliseconds 500
$eventSubscriber | Unregister-Event
$eventSubscriber.Action | Remove-Job
if(-not (Get-EventSubscriber)){
$Profile_Sum = Get-ChildItem -Path $Global:BackUp_Path -Recurse |
Measure-Object -Property length -Sum |
Select-Object -ExpandProperty Sum
$Size = try{if($Profile_Sum -lt 1048576){ $TinyByte = " {0:N2}" -f ($Profile_Sum / 1KB) + " KB"; $TinyByte }
elseif($Profile_Sum -gt 1048576 -and $Profile_Sum -lt 1073741824){ $MediumByte = " {0:N2}" -f ($Profile_Sum / 1MB) + " MB"; $MediumByte }
elseif($Profile_Sum -gt 1073741824){ $GiganticByte = " {0:N2}" -f ($Profile_Sum / 1GB) + " GB"; $GiganticByte } } Catch {}
$Begin_Time = Get-Item -Path $Global:BackUp_Path | Select-Object -ExpandProperty LastWriteTime
$End_Time = Get-Date -Format G
Get-Job | Remove-Job
[System.Windows.MessageBox]::Show("Copying Complete!`nStart Time: $Begin_Time `nEnd Time: $End_Time `nProfile Size copied: $Size")
}
} | Out-Null
}
I feel like I may have an idea due to the event itself being registered as a job but, not too sure how to go about it and have it wait until its done with ALL jobs before displaying the messagebox informing me when the copying is complete. Other than that, the script works just fine and anyone reading this can feel free to use it themselves. Heres the full Script:
Function PFL-UserBackUp{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$false,
ValueFromPipeLine=$true,
ValueFromPipeLineByPropertyName=$true)]
[Alias('CN','Computer','server','node')]
[ValidateLength(1, 15)]
[String[]]$ComputerName = $env:COMPUTERNAME )
Begin{
$Global:Shared_BackupPath = "\\server\share\"
}
Process{
Foreach($Computer in $ComputerName){
Try{
$PSSession = New-PSSession -ComputerName $Computer -ErrorAction Stop
[array]$User_List = Invoke-Command -ScriptBlock {
Get-ChildItem -Path "C:\Users" -Exclude Public, Default* |
Sort-Object -Property LastWriteTime -Descending } -Session $PSSession
$userinfo1 = foreach ($user in $User_List.name) {
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) { "NO DISPLAY NAME in ADUC" }
elseif($LASTEXITCODE -eq 2) { "ACCOUNT NOT in ADUC" }
elseif($LASTEXITCODE -eq 0) { $userinfo }
else { "Error occured" }
}
$(for($i=0; $i -lt $User_List.Count; $i++){
[pscustomobject]#{
'User Display Name ' = "$($i): $($userinfo1[$i])"
' NAME ' = $User_List.name[$i]
'Last Modified' = "$($User_List.LastWriteTime[$i])"
'Profile Size ' = Try{
$ProfilePath = $User_List.FullName[$i]
$Profile_Sum = Invoke-Command -ScriptBlock {
Get-ChildItem -Path $Using:ProfilePath -Recurse |
Where-Object {$_.PSParentPath -match "Documents|Desktop|Music|Videos|Downloads|Links|Pictures|Favorites|Contacts" -and $_.DirectoryName -notmatch "OneDrive" } |
Measure-Object -Property length -Sum |
Select-Object -ExpandProperty Sum } -Session $PSSession
if($Profile_Sum -lt 1048576){ $TinyByte = " {0:N2}" -f ($Profile_Sum / 1KB) + " KB"; $TinyByte }
elseif($Profile_Sum -gt 1048576 -and $Profile_Sum -lt 1073741824){ $MediumByte = " {0:N2}" -f ($Profile_Sum / 1MB) + " MB"; $MediumByte }
elseif($Profile_Sum -gt 1073741824){ $GiganticByte = " {0:N2}" -f ($Profile_Sum / 1GB) + " GB"; $GiganticByte } #Profile Size
} Catch { "$($Error[0].Exception.Message.Split('.')[2].Trim())!" }
}
} ) | Out-Host
Write-Host "Press 'Q' to quit."
$ii = Read-Host -Prompt "Enter Number of Profile to Back-Up"
$i = $ii.Trim() -split ","
if([String]::IsNullOrEmpty($i) -eq $true) { "Null string"; Break }
elseif($i.ToLower() -like "q*") {"Q was selected. Stopping script."; Break }
<#
" "
" Following Profiles will be Saved:"
" ------------------------------------"
foreach($i in $index) { "$($i.trim()): $($userinfo1[$i])" }
" "
$Confirm = Read-Host -Prompt "Are you sure you want to continue? [Y/N]"
if($Confirm.ToLower().TrimStart() -like "n*" -or $Confirm.ToLower() -like "q*"){Break}
if([String]::IsNullOrEmpty($Confirm.Trim()) -eq $true) { "Null string"; Break }#>
$Profile_Path = "C:\Users\$($User_List.name[$i])"
$Literal_Name = $userinfo1[$i].Replace('/','-')
$Global:BackUp_Path = "$Global:Shared_BackupPath$Literal_Name"
$Test_Path = Test-Path -Path $Global:BackUp_Path
if($Test_Path -eq $false){
New-Item -Path $Global:BackUp_Path -ItemType Directory | Out-Null
Start-Process $Global:BackUp_Path}
elseif($Test_Path -eq $true){
$Find_OldName = Get-ChildItem -Path "$Global:Shared_BackupPath" -Filter "$Literal_Name" -Directory |
Sort-Object -Property LastWriteTime -Descending |
Select-Object -ExpandProperty BaseName -First 1
$New_PathName = $Find_OldName + "1"
New-Item -Path "$Global:Shared_BackupPath" -Name $New_PathName -ItemType Directory -OutVariable Global:BackUp_Path | Out-Null #Global:BackUp_Path variable declared
$Global:BackUp_Path = $Global:BackUp_Path.FullName
Start-Process $Global:BackUp_Path}
$Global:Start_Time = Get-Date -Format G
#Favorites Copy
$FireFox_Favorites = "C:\Users\$($User_List.name[$i])\AppData\Roaming\Mozilla\Firefox\Profiles\*.default\places.sqlite"
$Chrome_Favorites = "C:\Users\$($User_List.name[$i])\AppData\Local\Google\Chrome\User Data\Default\Bookmarks"
$Chrome_Favorites2 = "C:\Users\$($User_List.name[$i])\AppData\Local\Google\Chrome\User Data\Default\Bookmarks.bak"
$Sticky_Notes = "C:\Users\$($User_List.name[$i])\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite"
$Favorites_Array = #($FireFox_Favorites,$Chrome_Favorites,$Chrome_Favorites2,$Sticky_Notes)
Foreach($File in $Favorites_Array){
$Test_File = Invoke-Command -ScriptBlock { Test-Path -Path $File }
if($Test_File -eq $true){
Copy-Item -Path $File -Destination $Global:BackUp_Path -Force -Recurse -FromSession $PSSession
}
}
#Folders Copy
$Folders = #('Desktop','Documents','Favorites','Links','Downloads','Music','Videos','Pictures','Contacts')
Foreach($Folder in $Folders){
#Create Arugments for seperate thread
$ArgumentsArray = $null
$ArgumentsArray = #()
$ArgumentsArray += "\\$Computer\c$\Users\$($User_List.name[$i])\$Folder"
$ArgumentsArray += $Global:BackUp_Path
$job = Start-Job -ScriptBlock { Copy-Item -Path $args[0] -Destination $args[1] -Force -Recurse } -Name $Folder -ArgumentList $ArgumentsArray
Register-ObjectEvent -InputObject $job -EventName StateChanged -Action {
#Start-Sleep -Milliseconds 500
$eventSubscriber | Unregister-Event
$eventSubscriber.Action | Remove-Job
if(-not (Get-EventSubscriber)){
$Profile_Sum = Get-ChildItem -Path $Global:BackUp_Path -Recurse |
Measure-Object -Property length -Sum |
Select-Object -ExpandProperty Sum
$Size = try{if($Profile_Sum -lt 1048576){ $TinyByte = " {0:N2}" -f ($Profile_Sum / 1KB) + " KB"; $TinyByte }
elseif($Profile_Sum -gt 1048576 -and $Profile_Sum -lt 1073741824){ $MediumByte = " {0:N2}" -f ($Profile_Sum / 1MB) + " MB"; $MediumByte }
elseif($Profile_Sum -gt 1073741824){ $GiganticByte = " {0:N2}" -f ($Profile_Sum / 1GB) + " GB"; $GiganticByte } } Catch {}
$Begin_Time = Get-Item -Path $Global:BackUp_Path | Select-Object -ExpandProperty LastWriteTime
$End_Time = Get-Date -Format G
Get-Job | Remove-Job
[System.Windows.MessageBox]::Show("Copying Complete!`nStart Time: $Begin_Time `nEnd Time: $End_Time `nProfile Size copied: $Size")
}
} | Out-Null
}
" "
Write-Output -InputObject "Copying will be done in background."
Write-Output -InputObject "You will be notified when copying is done."
} catch [System.Management.Automation.Remoting.PSRemotingTransportException]{
"Unable to connect to PC: $Computer `nError: $($Error[0].Exception.Message.Split('.')[2].Trim())!"
}
}
}
}
I removed some information that could get me in trouble but, it's all cosmetics.(:
EDIT: I must be on crack but, everything is working now. Only changes I made was clearing the global variables ($Global:var = $null) before assigning it a value. Thank you all for the suggestions. Another change i made was change Copy-Item to Robocopy instead.
To just answer your question:
Why is my if statement not being read properly?
Just before you evaluate Get-EventSubscriber your are cancelling your event subscription and thus deleting your event subscriber. Get-EventSubscriber therefore returns $null which evaluates to $true, when negated. In conclusion, the code after your if statement will always be executed immediately.
Commented code:
Register-ObjectEvent -InputObject $job -EventName StateChanged -Action {
$eventSubscriber | Unregister-Event # Here you cancel your event subscription
$eventSubscriber.Action | Remove-Job
if (-not (Get-EventSubscriber)) { # Therefore, Get-EventSubscriber returns $null; not $null evaluates to $true
...
The relevant part in the documentation of Unregister-Event:
The Unregister-Event cmdlet cancels an event subscription that was created by using the Register-EngineEvent, Register-ObjectEvent, or Register-WmiEvent cmdlet.
When an event subscription is canceled, the event subscriber is deleted from the session and the subscribed events are no longer added to the event queue. When you cancel a subscription to an event created by using the New-Event cmdlet, the new event is also deleted from the session.

Powershell remote installed softwares using workflow paralell

I am trying to convert my inventory script to be able to get a csv list of installed softwares on remote servers using workflows but I am not able to get it.
$tod = Get-Date;
$local = $PSScriptRoot +"\_Output\"+ "$((Get-Date).ToString('yyyyMMdd'))" + "\InstalledSoftwares\";
if(!(Test-Path -Path $local ))
{
New-Item -ItemType Directory -Path $local
}
$ItemList = Import-Csv $($PSScriptRoot + "\_HostList.CFG") -Header Srv -Delimiter ";"
Write-Host $ItemList.srv
workflow AllInstalledSoft {
ForEach -Parallel ($Serv in $ItemList.srv) {
#$Serv = $_.Srv
if (Test-Connection -computer $Serv -count(1) -quiet)
{
InlineScript { Write-Host $using:Serv "Is Reachable" -ForegroundColor Green
$file = $using:Serv+"_InstalledSoft"+"-{0:yyyyMMdd}.csv" -f $tod
$ExportFile = $local+$file
Get-WmiObject -Class Win32_Product -PSComputerName $using:Serv | select-object #{l="HostName";e={$using:Serv}},Name,InstallDate,InstallLocation,Vendor,Version,Caption,LocalPackage,IdentifyingNumber | Export-CSV -path $ExportFile -notypeinformation}
}
else
{
InlineScript { Write-Host $using:Serv "Is UnReachable" -ForegroundColor Red}
}
}
}
AllInstalledSoft
I cannot test but try this and see if it works. Don't try with the full hostname list, just reduce it to 5 computers to test if it works.
EDIT 3 :
$tod = (Get-Date).ToString('yyyyMMdd')
$local = $PSScriptRoot + "\_Output\" + $tod + "\InstalledSoftwares"
if(!(Test-Path -Path $local )){
New-Item -ItemType Directory -Path $local
}
$ItemList = Import-Csv $($PSScriptRoot + "\_HostList.CFG") -Header Srv -Delimiter ";" | Select-Object -Skip 1
workflow AllInstalledSoft {
param (
[parameter(Mandatory=$true)][array]$ItemList,
[parameter(Mandatory=$true)][string]$LocalExport,
[parameter(Mandatory=$true)][string]$Tod
)
ForEach -Parallel ($Serv in $ItemList) {
if(Test-Connection -ComputerName $Serv -Count 1 -Quiet){
$file = "$($Serv)_InstalledSoft-$Tod.csv"
$ExportFile = "$LocalExport\$file"
try {
Get-WmiObject -Class Win32_Product -PSComputerName $Serv -ErrorAction Stop | Select-Object PSComputerName,Name,InstallDate,InstallLocation,Vendor,Version,Caption,LocalPackage,IdentifyingNumber | Export-CSV -Path $ExportFile -NoTypeInformation
}
catch {}
}
}
}
AllInstalledSoft -LocalExport $local -ItemList $ItemList.Srv -Tod $tod

Invoke-Command: Null-value and positional parameter errors

I wanted to start a new thread for this, since I am using a different method in my code now. I have written a script that pings hundreds of devices and logs their online or offline status. It was taking an extremely long time to run, so I am now looking into using Invoke-Command to run the commands remotely on servers for each site (instead of all from the same server). I am receiving the following errors: "A positional parameter cannot be found that accepts argument 'Of'", "You cannot call a method on a null-valued expression", and this is happening for each server as it is iterating through them. Any ideas as to why this is happening? Thank you very much, here is my current code:
<#
.NOTES
===========================================================================
Created on: 11/17/2016 8:06 AM
Created by:
Organization:
Filename: Get-MPOSOfflinePrinters.ps1
===========================================================================
.DESCRIPTION
#>
#Define log file variables and remove any existing logs
$logfile = "D:\Logs\MPOSPrinterPingLog.txt"
$offlineprinters = "D:\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
Add-Content $logfile "Gathering server list"
#Compiling list of all MPOS Print Servers
$serverList = (Get-ADComputer -Filter "Name -like 'Q0*P30' -or Name -like 'Q0*P32'" -SearchBase "OU=Print,OU=Prod,OU=POS,DC=COMPANY,DC=NET").name | Sort-Object | Out-File C:\Temp\MPOS\MPOSPrintServers.txt
$serverListPath = "C:\Temp\MPOS\MPOSPrintServers.txt"
Add-Content $logfile "Compiling text file"
#Retrieve a list of MPOS Print servers from text file and set to variable $serverNames
$serverNames = Get-Content -Path $serverListPath
Invoke-Command -ComputerName $serverNames -ScriptBlock {
#Define log file variables and remove any existing logs
$logfile = "C:\Temp\MPOSPrinterPingLog.txt"
$offlineprinters = "C:\Temp\MPOSOfflinePrinters.txt"
$masteroffline = "\\a0345p689\d$\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
#process xml file to parse IP addresses for ping
$timestamp2 = (Get-Date -Format g)
Add-Content $logfile "$timestamp2 - Processing xml file from $serverName to parse data to csv"
$xml = [xml](Get-Content C:\ProgramData\Microsoft\Point Of Service\Configuration\Configuration.xml)
$PrinterNames = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{LogicalName=$_.LogicalName.Name}}
$PrinterIPs = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{HardwarePath=$_.HardwarePath}}
foreach ($PrinterIP in $PrinterIPs) {
$pingableIP = $PrinterIP.HardwarePath
If (Test-Connection $pingableIP -Quiet -Count 1) {
$timestamp3 = (Get-Date -Format g)
Add-Content $logfile "$timestamp3 - $serverName, $pingableIP is online and pingable"
}
Else {
$timestamp3 = (Get-Date -Format g)
Add-Content $offlineprinters "$timestamp3 - $serverName, $pingableIP is offline!"
}
Get-Content $offlineprinters | Out-File -FilePath $masteroffline -Append -NoClobber
} #foreach ($PrinterIP in $PrinterIPs) {
} #Invoke-Command -ComputerName $serverNames -ScriptBlock {

Powershell Workflow: Using if/else statement?

I am trying to use a workflow in order to make a script run faster by running a ping on several machines in parallel. Where I am getting stuck is trying to use my if/else statement within the workflow and adding log entries based on the results of the ping. Right now, it is not writing anything to the logs based on the ping results. Any assistance would be greatly appreciated. I am open to suggestions for different methods to do this, as long as they do not involve using a module. I want to stick with just Powershell code (I do not have permissions to install modules on the server where this would be running). Thank you! Here is my current code:
<#
.NOTES
===========================================================================
Created on: 10/6/2016 8:06 AM
Created by:
Organization:
Filename: Get-MPOSOfflinePrinters.ps1
===========================================================================
.DESCRIPTION
#>
$logfile = "D:\Logs\MPOSPrinterPingLog.txt"
$offlineprinters = "D:\Reports\MPOS\MPOSOfflinePrinters.txt"
If (Test-Path $logfile) {Remove-Item $logfile}
If (Test-Path $offlineprinters) {Remove-Item $offlineprinters}
Add-Content $logfile "Setting local path"
$localPath = "C:\Temp\MPOS"
Add-Content $logfile "Gathering server list"
$serverList = (Get-ADComputer -Filter "Name -like 'Q0*P30' -or Name -like 'Q0*P32'" -SearchBase "OU=Print,OU=Prod,OU=POS,DC=COMPANY,DC=NET").name | Sort-Object | Out-File C:\Temp\MPOS\MPOSPrintServers.txt
$serverListPath = "C:\Temp\MPOS\MPOSPrintServers.txt"
#Retrieve a list of MPOS Print servers from text file and set to $serverNames
Add-Content $logfile "Compiling text file"
$serverNames = Get-Content -Path $serverListPath
#Iterate through each of the server names
foreach ($serverName in $serverNames) {
Add-Content $logfile "Processing $serverName"
#Check if the server is online before doing the remote command
If (Test-Connection -ComputerName $serverName -Quiet -count 1) {
Add-Content $logfile "$serverName is online"
#copy config file from MPOS print to local server for processing
$timestamp1 = (Get-Date -Format g)
Add-Content $logfile "$timestamp1 - Copying xml file from server to local path"
$configPath = "\\$($serverName)\C$\ProgramData\Microsoft\Point Of Service\Configuration\Configuration.xml"
Copy-Item $configPath $localPath
#process xml file to parse IP addresses for ping
$timestamp2 = (Get-Date -Format g)
Add-Content $logfile "$timestamp2 - Processing xml file from $serverName to parse data to csv"
$xml = [xml](Get-Content C:\Temp\MPOS\Configuration.xml)
$PrinterNames = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{LogicalName=$_.LogicalName.Name}}
$PrinterIPs = $xml.selectNodes('//PointOfServiceConfig/ServiceObject/Device') | foreach {New-Object -TypeName psobject -Property #{HardwarePath=$_.HardwarePath}}
workflow Test-WFConnection {
param(
[string[]]$PrinterIPs
)
foreach -parallel ($PrinterIP in $PrinterIPs) {
$pingableIP = $PrinterIP.HardwarePath
If (Test-Connection -ComputerName $pingableIP -Quiet -Count 1 -ErrorAction SilentlyContinue) {
$timestamp3 = (Get-Date -Format g)
Add-Content -Path $logfile -Value ("$timestamp3 - $serverName, $pingableIP is online and pingable")
} #If (Test-Connection $pingableIP -Quiet -Count 1 -ErrorAction SilentlyContinue) {
Else {
$timestamp3 = (Get-Date -Format g)
Add-Content -Path $offlineprinters -Value ("$timestamp3 - $serverName, $pingableIP is offline!")
} #Else
} #foreach -parallel ($PrinterIP in $PrinterIPs) {
} #workflow Test-WFConnection {
Test-WFConnection -PSComputerName $PrinterIPs
} #If (Test-Connection -ComputerName $serverName -Quiet -count 1) {
Else {
Add-Content $logfile "$serverName is offline!"
} #Else
} #foreach ($serverName in $serverNames) {