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

OpenAuth2 access code doesn't come back from IE

$
0
0

Hi all,

I'm trying to get an OpenAuth2 access token in order to ultimately extract data from Google Analytics.

I can create a code url and pass that to the chrome browser and the request is serviced displaying the access code in the URL bar. I cannot however seem to grab this code using powershell as there is no ComObject for Chrome (as far as i can tell).

I've tried this using IE (which i can grab the URL using the ComObject) however the request doesn't seem to be serviced in IE and instead i get "This page can't be displayed" (the access code is not displayed in the URL string as it is with Chrome) 

Is there some setting i am missing in IE?

<code>

#Declarations
$clientId = "**"
$clientSecret = "**"
#return to us locally
$redirectUri = "http://localhost:8080/"
$email = "**"
$passwd = "**"

$grantType = "authorization_code"
$scope= "https://www.googleapis.com/auth/analytics"
$responseType = "code"

$getCodeUrl = "https://accounts.google.com/o/oauth2/auth?scope=$scope&redirect_uri=$redirectUri&response_type=$responseType&client_id=$clientId"


#Auto Sign in to Google accounts
 $ie = New-Object -ComObject InternetExplorer.Application
 $ie.Visible = $true
 $ie.navigate('http://www.gmail.com')
 while($ie.Busy)
 {
sleep -mil 100
 }
 if($ie.Document.Url -match 'Inbox')
 {
Write-Host 'Account already logged in'
#return $ie
 }
 else
 {
$ie.Document.getElementById("email").value=$email
$ie.Document.getElementByID("Passwd").value=$passwd
$ie.Document.getElementById("signin").Click()
while($ie.Busy)
{
sleep -mil 100
}
if($ie.Document.Url -match 'Inbox')
{
Write-Host 'Successfull login!' 
#return $ie
}
else
{
Write-Host 'Login failed!' 
}
}

#IE doesn't appear to return the access code like Chrome
$ie.navigate($getCodeUrl)

</code>


Issues with identity Members for Update-DistributionGroupMember

$
0
0

Hi there,

i'd like to do an import from a CSV and update the distributiongroupmember.

as i'm doing this, i have the CSV-File with the following content:

Name,OrganizationalUnit,Members,managedby,description
TEST-DG,contoso.com/Groups/Company,"user1,user2",user3,testgroup

the used command and also the error is:

[PS] C:\temp>Import-Csv C:\temp\distributiongroup.csv | foreach {Update-DistributionGroupMember -Identity $_.Name -Membe
rs $_.Members}
Couldn't find object "user1,user2". Please make sure that it was spelled correctly or specify a different object.
    + CategoryInfo          : NotSpecified: (:) [Update-DistributionGroupMember], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=SERVER1,RequestId=8d130f23-be48-44ee-b407-c4ac9aafdda0,TimeStamp=25.07.2014 11:
   17:46] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 8DA80102,Microsoft.Exchange.Management.Recipient
  Tasks.UpdateDistributionGroupMember

so i just realized, this is a problem of the identity MEMBERS, because there are two user-objects in it.

i tried it directly into the powershell with the following command and the same Error:

[PS] C:\temp>Update-DistributionGroupMember -Identity TEST-DG -Members "user1,user2"
Couldn't find object "user1,user2". Please make sure that it was spelled correctly or specify a different object.
    + CategoryInfo          : NotSpecified: (:) [Update-DistributionGroupMember], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : [Server=SERVER1,RequestId=85bcfbb2-05df-4837-bf08-115373ad0ea1,TimeStamp=25.07.2014 12:
   24:22] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 8DA80102,Microsoft.Exchange.Management.Recipient
  Tasks.UpdateDistributionGroupMember

as i tried not to use the quotes in the command, it worked just fine:

[PS] C:\temp>Update-DistributionGroupMember -Identity TEST-DG -Members user1,user2

Confirm
Are you sure you want to perform this action?
Updating the membership list on group "TEST-DG".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [?] Help (default is "Y"):

So, could anybody tell me - how to handle this with the Import-CSV not to have the quotes?

Best regards,

Adrian

Runspace opening multiple remote powershell connections and not closing them

$
0
0

Hello,

I hope this has not already been asked as I have been searching for good amount of time.

I have an asp.net site that runs some remote PowerShell scripts. Below is the code I Pass the script to. Everything works fine except it does not close all connections.

When I do a netstat -ao I see that each time this is called it leaves 2 sessions opened to the remote server. I go on the remote server and do a Get-PSSession and do not see any of the sessions opened. When stepping through the code, "pRunspace.Open()" creates 2 connections to the destination server, Then the "psresult = pShell.Invoke" creates another open connection. The Dispose() only closes one of the 3 connections. Upping the amount of connections or changing the idle time on the receiving server is not an option as I have already increased/lowered them and it still gets maxed connections. . iisreset clears the open connections. I have tried .disconnect() but the destination does not have PowerShell 3.0. Am I missing something stupid here? Is there a better way to go about this. 

Any help is appreciated.

Thank you,

Mike

Public Shared Function RunRemotePSScript(ByVal script As PSCommand, ByVal ServerURL As String, ByVal shellurl As String) As String

            Dim pCredential As PSCredential
            Dim pConnectionInfo As WSManConnectionInfo
            Dim pRunspace As Runspace
            Dim pShell As PowerShell
            Dim securepass As New System.Security.SecureString
            Dim serverUri As New Uri(ServerURL)
            Dim psresult As New System.Collections.ObjectModel.Collection(Of PSObject)
            For Each c In "Password"

                securepass.AppendChar(c)
            Next
            '-- set credentials      
            pCredential = New PSCredential("Domain\username", securepass)

            '-- set connection info
            pConnectionInfo = New WSManConnectionInfo(serverUri, shellurl, pCredential)
            '-- create remote runspace
            pRunspace = RunspaceFactory.CreateRunspace(pConnectionInfo)
            pRunspace.Open()
            '-- create powershell
            pShell = PowerShell.Create
            pShell.Runspace = pRunspace
            '-- add command to powershell
            pShell.Commands = script
            Try
                '-- invoke the powershell
                psresult = pShell.Invoke
                pShell.Dispose()
                pRunspace.Close()
                pRunspace.Dispose()
                Dim sb As String = ""
                For Each result As PSObject In psresult
                    sb &= result.ToString
                Next
                Return sb
                pShell.Dispose()
                pRunspace.Dispose()
                pRunspace.Close()
                pRunspace = Nothing

            Catch ex As Exception
                If Not IsNothing(pShell) Then
                    pShell.Dispose()
                End If
                If Not IsNothing(pRunspace) Then
                    pRunspace.Dispose()
                    pRunspace.Close()
                End If
                Return Err.Description
            End Try
        End Function

That is the netstat output I get after running through the function one time.

c:\Windows\system32>netstat -ao |findstr Server1
  TCP    MycomptuerIP:49307    RemoteServer1:http           ESTABLISHED     7632
  TCP    MycomptuerIP:49312    RemoteServer:http           ESTABLISHED     7632

Here is an example of how i call the function. 

Public Shared Function Set_UM_PinNumber(ByVal UserSamAccout As String, ByVal PinNumber As String) As String
            Try
                Dim output As String = ""
                Dim psh As New PSCommand
                psh.AddCommand("Set-UMMailboxPIN")
                psh.AddParameter("Identity", UserSamAccout)
                psh.AddParameter("Pin", (PinNumber))
                psh.AddParameter("PinExpired", 0)
                output = AD.ADWrapper.RunRemotePSScript(psh, "http://Server.domain.com/powershell?serializationLevel=Full", "http://schemas.microsoft.com/powershell/Microsoft.Exchange")
                If output = "" Then
                    Return "Pin Updated"
                Else
                    Return output
                End If
            Catch ex As Exception
                Return Err.Description
            End Try
        End Function


Problem calling 7zip from within a batch file from powershell

$
0
0

Hi all so I have a batch file that works fine locally on a machine it copies some files and a shortcut. However when I try to invoke it on another machine 7zip throws an error that says it cannot find the archive. Everything else seems to be working in the batch when I call it remotely though. Also I tried to specify the literal paths to the 7zip exe and the zipped files with no luck.

Batch file:

:: Installs Screencast-O-Matic_1.4
:: Approximate Disk Space Required = [Archive 77.2 MB] + [Extracted Temp 77.2 MB] + [Installed Size 77.2 MB]
:: Approximate Runtime = 

:: Prepares environment for batch file
@ECHO OFF
CLS
SETLOCAL


:: Stages Log Directory

:: Change Me!
SET APP_NAME=Screencast-O-Matic_1.4
::

:: Script Variables
SET RUNID=%RANDOM%
SET LOG_DIR=C:\Windows\Temp\SCCM_Logs\%APP_NAME%_%RUNID%
MKDIR %LOG_DIR%
SET LOG=%LOG_DIR%\%APP_NAME%_%RUNID%.log
SET TEMPDIR=C:\Windows\Temp\%APP_NAME%

:: Time Stamp In Log
ECHO %APP_NAME% > %LOG%
ECHO Start Script >> %LOG%
TIME /t >> %LOG%

:: Determines system architecture
FOR /F "tokens=2 delims==" %%A IN ('wmic Path Win32_Processor Get AddressWidth /Format:list') DO SET OSB=%%A
IF %OSB%==32 ECHO Install 32-Bit >> %LOG%
IF %OSB%==64 ECHO Install 64-Bit >> %LOG%

:: Creates Temporary Directory
IF EXIST %TEMPDIR% RMDIR %TEMPDIR% /S /Q
MKDIR %TEMPDIR%

:: Check for pending reboot
SET PENDING_CHECK=1
REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager" /v PendingFileRenameOperations > %LOG_DIR%\PendingCheck.log || SET PENDING_CHECK=0
IF %PENDING_CHECK%==1 (
	ECHO Pending Reboot Detected >> %LOG%
)

:: Check for existing install
ECHO Checking for existing install >> %LOG%

:: Detection: Adjust as necessary
IF EXIST "C:\Program Files\Screencast-O-Matic" (
	ECHO Software exists! >> %LOG%
	GOTO END
)

ECHO Existing installation not found, continuing with install... >> %LOG%


:BEGIN
7z.exe x "Screencast-O-Matic.7z" -o%TEMPDIR% -y > %LOG_DIR%\extraction_results.log
MKDIR "C:\Program Files\Screencast-O-Matic"
ROBOCOPY "%TEMPDIR%" "C:\Program Files\Screencast-O-Matic" /E /LOG:"%LOG_DIR%\Primary.log"
MKDIR "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Screencast-O-Matic"
ROBOCOPY "%TEMPDIR%" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Screencast-O-Matic" "Screencast-O-Matic.lnk"

:END

:: Removes Temporary Directory
ECHO Remove Temporary Files >> %LOG%
TIME /t >> %LOG%
RMDIR %TEMPDIR% /S /Q

ECHO End Script >> %LOG%
TIME /t >> %LOG%

ENDLOCAL

Powershell script to call batch (I know it's ugly I just threw it together) :

$computers = Get-Content 'C:\Users\cody-horton\Desktop\complist.txt'
$date = Get-Date

$item1 = "C:\Users\cody-horton\Desktop\Vmware_Files\Screencast O Matic"
#$item2 = "C:\Users\cody-horton\Desktop\Vmware_Files\Powershell_Installs\Unity"

$job1 =  {cmd /c "C:\Screencast O Matic\install.cmd"}
#$job2 =  {cmd /c "C:\Construct_2\install.cmd"}

if(!(Test-Path C:\users\cody-horton\Desktop\fails.txt)){
    New-Item -Path C:\users\cody-horton\Desktop -Name fails.txt –ItemType File
}

$computers = $computers | Sort-Object
Write-Host $computers

foreach($computer in $computers){
    
    if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet)){
        Add-Content -Path C:\users\cody-horton\Desktop\fails.txt -Value "$($computer) Error Connecting"
    }
    else{
        Copy-Item $item1 "\\$($computer)\C`$\" -Recurse
        #Copy-Item $item2 "\\$($computer)\C`$\" -Recurse
        Invoke-Command -ComputerName $computer -ScriptBlock $job1 -AsJob
        write-host "$computer" -ForegroundColor Green
    }

}

Get-Job | Wait-Job

<#
foreach($computer in $computers){
    if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet)){
        Add-Content -Path C:\users\cody-horton\Desktop\fails.txt -Value "$($computer) Error Connecting"
    }
    else{
        Invoke-Command -ComputerName $computer -ScriptBlock $job2 -AsJob
        write-host "$computer Construct" -ForegroundColor Green
    }

}

Get-Job | Wait-Job
#>

foreach($computer in $computers){
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet)){
        Remove-Item "\\$($computer)\C`$\Screencast O Matic" -Recurse
        #Remove-Item "\\$($computer)\C`$\Construct_2" -Recurse
    }
}

Add-Content -Path C:\users\cody-horton\Desktop\fails.txt -Value "Done $($date)"

Thanks for any help!! I'm guessing it's getting confused and is trying to find it on my machine possibly.

Deleting Temporary Internet Files

$
0
0
I'm working on a script to delete temporary internet files from all profiles on a given list of servers (namely our terminal servers that keep getting filled up with garbage). I've got it working but I get lots of errors during the deletions because the temp files have file names larger than 260 characters.

Here's what I have:

# Declare the servers
# ===================

#$tservers = [real server list]



# @ TESTING BLOCK
# @
$tservers = [test machines]
# @
# @




#Display a little info on how many profiles you find
# ==================================================
foreach ($server in $tservers) {

    write ''
    write "Server: $Server"
    $profiles = get-childitem "\\$server\C$\Documents and Settings" -force
    write "Found $($profiles.count) profiles on $server."

    # Delete the temporary internet files for each
    # ============================================
    foreach ($userprofile in $profiles) {
    write "Deleting $server\$userprofile temp files..."
    remove-item "$($userprofile.fullname)\local settings\temp\*" -force -recurse
    remove-item "$($userprofile.fullname)\local settings\temporary internet files\content.ie5\*" -force -recurse
    }
}

Ideally I'd like to instantiate IE on the remote box and delete the temp files the right way, but I don't know if that's possible in PS. Any better ideas?

(Inexistent cmdlet) Get-Partition -Attributes

$
0
0

Hy,

I've been working with partitions, changing type ID's and atributes, and realized that I had to use partdisk, because although I found set-partition to change the values, there seems to be no way to show the current values only using PS.

Is this correct? Where can I suggest this?


Search-Mailbox -SearchQuery not filtering time correctly

$
0
0

This question was posted on the Exchange Administration, Monitoring and Performance forum and they reccomended to post it here as well:

After reading: http://technet.microsoft.com/en-us/library/dd298173(v=exchg.150).aspx

which links off to: http://msdn.microsoft.com/library/ee558911%28v=office.15%29.aspx

I made the following PowerShell script to test what is captured before I use the cmdlet with the -DeleteContent parameter

$A=Get-Date '18/7/2014'

$Start=Get-Date $A.ToUniversalTime() -Format yyyy-MM-ddThh:mm:ss
$End=Get-Date $A.AddDays(1).ToUniversalTime() -Format yyyy-MM-ddThh:mm:ss

$SearchQuery='Received>="'+$Start+'" AND Received<"'+$End+'"'

Search-Mailbox -Identity 'mailbox@domain' -SearchQuery $SearchQuery -TargetMailbox 'targetmailbox@domain' -TargetFolder Inbox -LogOnly -LogLevel Full

The results I get back are all the emails between 17/7/2014 12:00 AM - 18/7/2014 12:00 AM

When I thought it should be the emails between 17/7/2014 2:30 PM - 18/7/2014 2:30 PM (Our time zone is +9:30)

Does the query I'm passing to -SearchQuery need tweaking or am I doing something else wrong?

To help with readability, the $SearchQuery variable expands out to this:

Received>="2014-07-17T02:30:00" AND Received<"2014-07-18T02:30:00"

how to detect whether powershell remoting is enabled/disabled on local machine?

$
0
0

These are two ways I can think of about checking whether powershell remoting is enabled/disabled on local machine:

1. create a loop back runspace to local machine and try running a cmdlet in this remote runspace. If this cmdlet works, then the remoting is enabled. This way will be time-consuming.

2. check each component of powershell remoting, such as whether winrm is started, whether firewall exception is configured, whether listener is added... This way could be broken by future powershell update.

Is there a decent way to check whether powershell remoting is enabled/disabled on local machine?

 

 


powershell get system metrics

$
0
0
Is there a simple way to invoke GetSystemMetrics(SD_) from Powershell?

Kara

How to use substring on a property within a "select -expand properties" statement

$
0
0

Apologies if this is a dumb question - I'm just familiarizing myself with Powershell.

I have an existing script which queries groups in AD. It outputs some attributes of the groups to a CSV file.

I'm trying to modify it a little bit - one of the attributes it returns is the distinguishedname of each group. I'm trying to get it to chop off the first part ("CN=groupname,"), leaving the OU path of each group.

Here is the original line that I think needs to be modified:

$AllGroups = $GroupAccounts | select -Expand Properties | select @{n='GroupName';e={$_.name}}, @{n='Description';e={$_.description}}, @{n='DN';e={$_.distinguishedname}}
Based on what I've gleaned so far about Powershell, I figured I would use the substring function, along with the length of the group's name (plus 4 to account for the "CN=" and the first comma). But every variation that I've tried returns nothing at all for the last property ("DN").  

Any suggestions?


scipt to test svc status on multiple computers output to html and refresh

$
0
0

script to:

1) test net logon svc on multiple computers

2) output results to html iframe  for computers where service is not running

3) be able to have the script update every 30 seconds

why would an alias of a cmdlet report fewer parameter properties than the cmdlet itself?

$
0
0

Why would an alias of a cmdlet report fewer parameter properties than the cmdlet itself? 

Consider the transcript below.  Write-Output & echo have the same number but Get-ChildItem and gci do not.

<#c:#> cat alias:gci
Get-ChildItem<#c:#> ((get-command get-childitem).parameters).count
23<#c:#> ((get-command gci).parameters).count
17<#c:#> cat alias:echo
Write-Output<#c:#> ((get-command write-output).parameters).count
9<#c:#> ((get-command echo).parameters).count
9

Save webpage to xps file by using $ie.ExecWB function

$
0
0
when save webpage to xps file by using $ie.ExecWB(6,2) function, it only saves the first page. It seems when print to xps file, it has default selection of "Page 1" or "Current Page". Is there a way to change to save "All Pages" to xps file? Thanks

Logical Disk Performance counter for cluster shared volume on Hyper-V

$
0
0

Hello All,

I am trying to collect counters like latency, queuelength from Win32_PerfFormattedData_PerfDisk_LogicalDisk WMI class.

Output of "Name" attribute for logical disks in this class as below:


Name: _Total
Name: C:
Name: E:
Name: HarddiskVolume1
Name: Q:

Name here doesn't show the actual label so I queried Win32_Volume class and wanted to join with performance WMI class. Out put of Win32_Volume is as below:

Caption: E:\
Label: New Volume
Name: E:\

Caption: Q:\
Label: Quorum
Name: Q:\

Caption: C:\
Label: Voume C
Name: C:\

Caption: F:\
Label: SAN
Name: F:\

Please note that "Name" attribute matches for all except one with label "SAN". This is cluster shared volume and "Name" attribute value is "HardDiskVolume1" in Win32_PerfFormattedData_PerfDisk_LogicalDisk class.

Is this is a configuration issue or any other alternative to get volume label and corresponding performance counters.

Thanks in advance

Regards,

Udupa

power shell like what is purpose

$
0
0

someone help me how to understand power shell like what is purpose, how to pull report on one machine \multiple machine, how to change settings on one machine/multiple machines again troubleshooting tips .finally focus on SCCM 2012 R2 different activity using power shell


sccmghost@hotmail.com


Compare-object bug? Results differ when a lot of files are compared

$
0
0

I am comparing 2 folders, where files match on .basename. For example want to compare file0001.pdf in share01 to file0001.dgn in share02. I want to compare using LastWriteDate.

If only one object exists in -referenceObject and -differenceObject. This is the result:

PS C:\Users\username> Compare-Object -ReferenceObject $tstdgn -DifferenceObject $tstpdf -Property LastwriteDate -IncludeEqual

LastwriteDate                                                                                                                   SideIndicator                             2012-10-17                                                                                                                      ==           

This is the content of the variables:

PS C:\Users\username> $tstpdf

LastWriteTime : 17-10-2012 11:39:04
Extension     : .PDF
Parentfolder  : \fileserver\share01
BaseName      : file0001
FileName      : file0001.PDF
LastWriteDate : 2012-10-17

PS C:\Users\username> $tstdgn

LastWriteTime : 17-10-2012 11:39:12
Extension     : .DGN
Parentfolder  : \\fileserver\share02
BaseName      : file0001
FileName      : file0001.DGN
LastWriteDate : 2012-10-17

But if i have a lot of files in each variable, then this is the result:

PS C:\Users\username> (Compare-Object -ReferenceObject $NewAllDGN -DifferenceObject $NewAllPDF -Property LastwriteDate -PassThru) | where {$_.basename -eq "file0001"}


LastWriteTime : 17-10-2012 11:39:04
Extension     : .PDF
Parentfolder  : \fileserver\share01
BaseName      : file0001
FileName      : file0001.PDF
LastWriteDate : 2012-10-17
SideIndicator : =>

This is the content of the variables:

PS C:\Users\username> $NewAllDGN.count
37429

PS C:\Users\username> $NewAllDGN | where {$_.basename -eq "file0001"}
LastWriteTime : 17-10-2012 11:39:12
Extension     : .DGN
Parentfolder  : \\fileserver\share02
BaseName      : file0001
FileName      : file0001.DGN
LastWriteDate : 2012-10-17

PS C:\Users\username> $NewAllPDF.count
15281

PS C:\Users\username> $NewAllPDF | where {$_.basename -eq "file0001"}
LastWriteTime : 17-10-2012 11:39:04
Extension     : .PDF
Parentfolder  : \\fileserver\share01
BaseName      : file0001
FileName      : file0001.PDF
LastWriteDate : 2012-10-17

what am i missing here?


/Frederik Leed

Invoke-command -scriptblock not working as intended

$
0
0

Hi all, I've got a piece of code, I'm trying to install a program on a remote server yet the start script part isn't working. here is my piece of code..

#Variables
$computername = Get-Content 'F:\Kuliah\Ide TA\TAku\Coba\Comp-List.txt'
$sourcefile = 'F:\INSTALLER\npp.6.3.Installer.exe'
#This section will install the software 
#$mycreds = Get-Credential
foreach ($computer in $computername) 
{
	$destinationFolder = "\\$computer\C$\Temp"
	#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
	if (!(Test-Path -path $destinationFolder))
	{
		New-Item $destinationFolder -Type Directory
	}
	Copy-Item -Path $sourcefile -Destination $destinationFolder
	Invoke-Command -ComputerName $computer -ScriptBlock {Start-Process 'c:\temp\npp.6.3.Installer.exe'}
}

the copy part works, and properly copies my program. yet the invoke command isn't working on the remote server. though it works completely fine if run at my own pc.


Powershell - Export permissions for folder and share?

$
0
0

I need to export all the share and folder level permission on one of my windows 2008 file servers. I have tried the command below and it give me all the folder and file level permissions.

Get-ChildItem "X:\Share" -recurse | Get-Acl | export-csv c:\djk\share_folder_permission.csv

I dont want file level permissions, only share and folder level.  Can you help?

 

 

Network query related to deployment on Azure using powershell

$
0
0

Hi,

Firstly, I apologize as the question may sound very naive but somehow I am not able to get clear explanation (or may be I am missing something very basic).

I have a package (.pkg) present on a remote machine (on a corporate network). I need to upload this to Azure using powershell. I write a basic Powershell script (on my local computer connected to a home network) which will upload this .pkg to a cloud service on Azure. But first, I need to upload the .pkg to Azure storage to avoid any bandwidth issues from where the package will be picked-up. Hence, I have written a script to upload .pkg to azure storage first. 

As I see, the bytes (.pkg) on my home network getting downloaded on my local machine and then it gets uploaded to blob storage (upload/download uses my home network). Is there a way/possibility where the files can just be moved/copied from that corporate network to blob storage directly? As I get it from few others, this is how OS behaves, Is it true? Can someone please explain this?

Thanks!

equality operator inconsistency?

$
0
0

Found an irritating gotcha…  Imagine you’re querying a table with Server names and SQL versions (full-dot versions like 11.0.3128.0, 9.00.4053.00, 8.00.2282, etc…)

Here’s the problematic piece of my script (logic removed and write-host embedded for illustration) – basically I want to execute 2 different logic blocks (containing different SQL statements for AGs) depending on the SQL Version.

$Query2 = "SELECT distinct(ServerNames), substring([version], 1, charindex('.' , [version], 1 ) -1) [version] from DatabaseChecks..SQLServers where BackupCheck=1"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$CentralServer; Integrated Security=SSPI")

$SqlConnection.Open()

$cmd = new-object System.Data.SqlClient.SqlCommand ($Query2, $SqlConnection);

$ServerList = $cmd.ExecuteReader();

while ($ServerList.Read())

{

  $ServerName = $ServerList.GetValue(0).ToString().ToUpper().Trim();

  $Version = $ServerList.GetValue(1);

 

  # SQL Server 2000/2005/2008

  If($Version -le 10) {

  Write-Host "Processing $ServerName $Version     -le 10 logic"

  }

  # SQL Server 2012/2014

  If($Version -ge 11) {

  Write-Host "Processing $ServerName $Version     -ge 11 logic"

  }

}

I get some wonky results for 2000 (8) and 2005 (9):

Processing SERVER-A 8     -ge 11 logic
Processing SERVER-B 10     -le 10 logic
Processing SERVER-C 10     -le 10 logic
Processing SERVER-D 9     -ge 11 logic
Processing SERVER-E 11     -ge 11 logic

If I change the query to left pad single-digit values with a zero, I get the expected execution:

$Query2 = "SELECT distinct(ServerNames), right('0' + rtrim(substring([version], 1, charindex('.' , [version], 1 ) -1)), 2) [version] from DatabaseChecks..SQLServers where BackupCheck=1"

Processing SERVER-A 08     -le 10 logic
Processing SERVER-B 10     -le 10 logic
Processing SERVER-C 10     -le 10 logic
Processing SERVER-D 09     -le 10 logic
Processing SERVER-E 11     -ge 11 logic

I tried all sorts of things with my $Version variable – Trim(). ToString(), just using the straight up value… tried wrapping my comparison numbers (10 and 11) in single and double quotes – nothing worked until I manipulated what I was actually getting back from SQL. Googled to try to find any reports of this behavior but found nothing.  Thoughts??

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>