How to get an variable output from remote pssession - arrays

I have a script to get virtual harddisk info from vmm, im executing it remotely from a server, currently im unable to get the variable value outside of the pssession in the local host, could you please help me out with achieveing the same.
PS C:\Windows\system32> enter-pssession iscvmm02
[iscvmm02]: PS C:\Users\su\Documents>Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager
[iscvmm02]: PS C:\Users\su\Documents>$hide= Get-VMMServer -ComputerName "iscvmm02.corp.avanade.org"
[iscvmm02]: PS C:\Users\su\Documents>$VM = Get-VM | where { $_.ComputerNameString -contains "idpsm02.corp.air.org" }
[iscvmm02]: PS C:\Users\su\Documents>$harddisk=$VM.VirtualHardDisks
[iscvmm02]: PS C:\Users\su\Documents>$h=$harddisk.length
[iscvmm02]: PS C:\Users\su\Documents>for($i=0;$i-lt$h;$i++){
New-Variable -Name "HardDiskType_$i" -value $harddisk[$i].vhdtype
New-Variable -Name "HardDiskLocation_$i" -value $harddisk[$i].Location
}
[iadpscvmm02]: PS C:\Users\su\Documents>Exit-PSSession
PS C:\Windows\system32>$harddisktype_0
PS C:\Windows\system32>$harddisklocation_0
as you can see both the variable output's give null value, im unable to retain the values

This example gets listing from remote computer's C drive and assigns it into a local variable. So tune your VMM script accordingly.
$session = New-PSSession -ComputerName RemoteSystem
Invoke-Command -Session $session -ScriptBlock { $remoteC = gci c:\ }
# This shouldn't print anything.
$localC
# Print the result on remote computer an assing its output to localC variable
$localC = Invoke-Command -Session $session -ScriptBlock { $remoteC }
# Print the local variable, it should contain remoteC data.
$localC

Related

Use script who use functions stocked in another ps1 with Start-job

I'm trying a little WPF interface with powershell for compare two files. For do that, I want start 2 jobs with script who was stocked in "Jobs.ps1"
Param(
$PathFile1,
$PathFile2,
$Json
)
$Hash = CreateHashConverted -Path $PathFile1 -Fichier $Json
$List = [System.Collections.ArrayList]::New()
$List = CompareFile -Path $PathFile2 -Hash $Hash
return $List
But actually, "CreateHashConverted" and "CompareFile" uses somes functions who was stocked in "JsonFunctions.ps1" and "ReadFunctions.ps1"
When i try to use my start job
$null = Start-Job -Name "1vers2" -FilePath "$PSScriptRoot\..\Logique\Jobs.ps1" -ArgumentList $txtb_file1,$txtb_file2,$lb_LISTE.SelectedItem
My job doesn't know CreateHashConverted and CompareFile
Thank's for help
Use the -InitializationScript parameter to import the function definitions needed by the job:
$null = Start-Job -Name "1vers2" -InitializationScript { . "$PSScriptRoot\..\Logique\JsonFunctions.ps1"; . "$PSScriptRoot\..\Logique\ReadFunctions.ps1" } -FilePath "$PSScriptRoot\..\Logique\Jobs.ps1" -ArgumentList $txtb_file1,$txtb_file2,$lb_LISTE.SelectedItem

Run multiple *.sql query files log to file

My goal is to have a PowerShell script run several Sqlquery.sql files against a specific SQL server and then log the output to a log file.
I can't get the logging to work and I don't know what I'm missing. My log file is always empty and I'm at a loss for that I am missing.
Contents of C:\Temp:
Build1.SQL
Build2.SQL
Build3.sql
Build4.sql
Build5.SQL
Build6.SQL
$PatchPostConvSQLScripts = Get-ChildItem -Path C::\Temp -Filter *.sql -Name
$Queries = $PatchPostConvSQLScripts
foreach ($query in $Queries){
Write-Host "Starting: $query"
Invoke-Sqlcmd -ServerInstance $DBServer -InputFile $query |
Out-File "C:\TEMP\scriptResults.log"
Write-Host "Completed: $query"
}
Once I get it logging to a file, I'll need to get a newline each time with a `n`r, but baby steps right now.
Is there a better way to do this that I just don't know?
The main reason you got nothing in log file is that Output-File rewrite whole data in it on each run. Try to use -Verbose as mentioned in answer by TechSpud to collect print/server statements, or write output to temp file and Add-Content to main log file:
$DBServer = "MYPC\SQLEXPRESS"
$sqlPath = "C:\TEMP\"
$log = "scriptResults.log"
$tempOut = "temp.log"
$files = Get-ChildItem -Path $sqlPath -Filter *.sql -Name
foreach ($file in $files){
Write-Host "Starting: $file"
Invoke-SQLcmd -ServerInstance $DBServer -InputFile $sqlPath$file | Out-File $sqlPath$tempOut
Get-Content $sqlPath$tempOut | Add-Content $sqlPath$log
Write-Host "Completed: $file"
}
Firstly, as #Ben Thul has mentioned in his comment, check that your SQL files actually output something (a resultset, or messages), by running them in Management Studio.
Then, you'll need to use the -Verbose flag, as this command will tell you.
Get-Help Invoke-Sqlcmd -Full
Invoke-Sqlcmd does not return SQL Server message output, such as the
output of PRINT statements, unless you use the PowerShell -Verbose parameter.
$Queries = Get-ChildItem -Path C::\Temp -Filter *.sql -Name
Clear-Content -Path "C:\TEMP\scriptResults.log" -Force
foreach ($query in $Queries){
Write-Host "Starting: $query"
Invoke-Sqlcmd -ServerInstance $DBServer -InputFile $query -Verbose |
Add-Content -Path "C:\TEMP\scriptResults.log"
Write-Host "Completed: $query"
}

Powershell: WMI Ping piped to variable

I'm having some difficulties in getting my PowerShell script to work as I'd like it to and after much jiggery-pokery here I am.
My overall aim is fairly simple, unfortunately I'm somewhat of a PowerShell noob!
I'm trying to determine the name, manufacturer and model of all of the systems in our estate without having to walk around staring at lots of tin.
I've constructed the following based solely on my bad knowledge of scripting and I've hit a snag.
My idea was to pass DNS/IP information from a CSV into a variable which I can then use in turn to perform the WMI query based on the Ping results.
False Ping response = do not query
True Ping response = perform WMI query
Here is what I've got so far...
Test-connection -computername
foreach ($Ping in $Hosts)
{
test-connection -computername $Ping.IP -count 1 -quiet
if ($Ping.StatusCode -eq 0)
{Get-WmiObject win32_computersystem -computername $ip.Name | select Name,Manufacturer,Model } out-file c:\CSV\Test1.csv -ea SilentlyContinue}
else
{write-host $Hosts.Status Offline}
}
Assuming you have file C:\CSV\Hosts.csv with contents as described:
computer1.mydomain.com
computer2.mydomain.com
With the following script you'll get file C:\CSV\Results.csv:
$Hosts = Get-Content "C:\CSV\Hosts.csv"
foreach ($PingIP in $Hosts)
{
$alive = Test-Connection -ComputerName "$PingIP" -count 1 -quiet
if ($alive)
{
Get-WmiObject Win32_ComputerSystem -ComputerName "$PingIP" | Select Name, Manufacturer, Model | Out-File "C:\CSV\Results.csv" -ea SilentlyContinue
}
else
{
Write-Output "$PingIP offline"
}
}

Get $webclient.downloadstring to write to text file in Powershell

I'm not a programmer/scripter. I just need to get the following script to write to a file:
[CmdletBinding()]
param ()
# Create a web client object
$webClient = New-Object System.Net.WebClient
# Returns the public IP address
$webClient.DownloadString('http://myip.dnsomatic.com/')
I've tried out-file and export-csv but it write a blank file. I'm sure it's something simple...but having no knowledge makes it difficult for me.
You could also use the DownloadFile method:
$webClient.DownloadFile('http://myip.dnsomatic.com/', 'c:\ip.txt')
The add-content cmdlet should do what you want.
Assuming $webClient.DownloadString('http://myip.dnsomatic.com/') returns a string, try:
Add-Content -Path $filename -Value $webClient.DownloadString('http://myip.dnsomatic.com/')
Reference:
http://technet.microsoft.com/en-us/library/dd347594.aspx
$PublicIP="C:\PublicIP.txt"
$WebClient=New-Object net.webclient
$String=$WebClient.DownloadString("http://checkip.dyndns.com") -replace "[^\d\.]"
If (Test-Path $PublicIP) {
Remove-Item $PublicIP
}
New-Item $PublicIP -type file
Add-Content -Path $PublicIP -Value $String

Powershell Script using Invoke-SQL command,needed for SQL job, the SQL Server version of Powershell is somewhat crippled, is there a workaround?

Full Question: Have Powershell Script using Invoke SQL command, using snappins, I need them to be included in a SQL job, the SQL Server version of Powershell is somewhat crippled, does anyone know a workaround?
From what I have gathered, SQL Management Studio's version of powershell is underpowered, not allowing for the use of snappins, as such it does not recognize the cmdlets that I used in the script. I have tried running it in the job as a command line prompt rather than a Powershell script, which causes the code to work somewhat, however I check the history on the job and it says that invoke-sql is still not a recognized cmdlet. I speculate that because I am running the code on a remote server, with different credentials than my standard my profile with the snappins preloaded isn't being loaded, though this is somewhat doubtful.
Also, as I am a powershell rookie, any advice on better coding practices/streamlining my code would be much appreciated!
Code is as follows:
# define parameters
param
(
$file = "\\server\folder\file.ps1"
)
"invoke-sqlcmd -query """ | out-file "\\server\folder\file.ps1"
# retrieve set of table objects
$path = invoke-sqlcmd -query "select TableName from table WITH (NoLock)" -database db -server server
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$so = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
$so.DriPrimaryKey = $false
$so.Nocollation = $true
$so.IncludeIfNotExists = $true
$so.NoIdentities = $true
$so.AnsiPadding = $false
# script each table
foreach ($table in $path)
{
#$holder = $table
$table = get-item sqlserver:\sql\server\default\databases\database\tables\dbo.$($table.TableName)
$table.script($so) | out-file -append $file
}
(get-content "\\server\folder\file.ps1") -notmatch "ANSI_NULLS" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch " AS "| out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -notmatch "Quoted_" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\) ON \[PRIMARY\].*", ")" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "\[text\]", "[nvarchar](max)" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace " SPARSE ", "" | out-file "\\server\folder\file.ps1"
(get-content "\\server\folder\file.ps1") -replace "COLUMN_SET FOR ALL_SPARSE_COLUMNS", "" | out-file "\\server\folder\file.ps1"
""" -database database -server server" | out-file "\\server\folder\file.ps1" -append
So I figured out the answer to my own question. Using this site: http://www.mssqltips.com/tip.asp?tip=1684 and
http://www.mssqltips.com/tip.asp?tip=1199
I figured out that he was able to do so using a SQL Server Agent Proxy, so I followed the yellow brick road, and basically I set up a proxy to my account and was able to use the external powershell through a feature. A note, you need to create a credential under the securities tab in object explorer prior to being able to select one when creating the proxy. Basically I ended up creating a proxy named powershell, using the powershell subsystem, and use my login info to create a credential. VOILA!
You have to add the snapins each time. In your editor you likely already have them loaded from another script/tab/session. In SQL Server you will need to add something like this to the beginning of the script:
IF ( (Get-PSSnapin -Name sqlserverprovidersnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin sqlserverprovidersnapin100
}
IF ( (Get-PSSnapin -Name sqlservercmdletsnapin100 -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin sqlservercmdletsnapin100
}
I'm not sure the error you are trying to workaround - can you post that?
Have you tried this from a PowerShell prompt?
Add-PSSnapin SqlServerCmdletSnapin100

Resources