"variableB = $+variableA"" - powershell

Script:
$ZZSG1 = "SGvcenter.domain.com"
$ZZBLR2 = "BlgvCenter.domain.com"
$ZZUS2 = "USvCenter.domain.com"
$siteid = Read-Host "enter physical site id eg:ZZUS2"
$siteids = "ZZSG1","ZZBLR2","ZZUS2"
if ($siteids -notcontains $siteid) {
Write-Host "siteid not found"}
else{
$SID = "$"+"$siteid"
Write-Host "$siteid contains this vCenter $SID"}
$SID
Output:
ZZSG1 contains this vCenter $ZZSG1
$ZZSG1
Expected Output:
ZZSG1 contains this vCenter SGvcenter.domain.com
SGvcenter.domain.com

Your definition of $SID is going to be set a string of the name variable not the value of the variable. Try something like this to get the variable value.
Replace:
$SID = "$"+"$siteid"
with:
$SID = (Get-Variable $siteid).value

Related

Changing HideFastUserSwitching value in PowerShell script using Invoke-Command on a remote machine

I have written a below script which prompts user to enter a remote computer name, checks "HideFastUserSwitching" value in the registry of the computer and changes it if user wishes so.
The script does its job, I have tested to change the value from 1 to 0 on one machine. But if I run the script again and try to change it back to 1, it doesn't do that. The value stays 0.
Could you please help me figure out why does this happen? If you have remarks about other pieces of code in this script, you are welcome to give me some advise, it will be appreciated.
$PN = (Read-Host "Enter PN#").ToUpper().Trim()
$path = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System"
$regKeyName = "HideFastUserSwitching"
$hideFastUserSwitchingValue = $null
Function getHideFastUserSwitchingValue {
$regKeyValue = $null
$parameters = #{
ComputerName = $PN
ScriptBlock = {
Param ($path, $regKeyName)
Get-ItemProperty -Path $path -Name $regKeyName | Select-Object -ExpandProperty $regKeyName
}
ArgumentList = $path, $regKeyName
}
Invoke-Command #parameters
}
Function setHideFastUserSwitchingValue($value) {
$parameters = #{
ComputerName = $PN
ScriptBlock = {
Param ($path, $regKeyName)
Set-ItemProperty -Path $path -Name $regKeyName -Value $value
}
ArgumentList = $path, $regKeyName
}
Invoke-Command #parameters
}
$hideFastUserSwitchingValue = getHideFastUserSwitchingValue
$yesNo = (Read-Host "HideFastUserSwitching value is $hideFastUserSwitchingValue. Do you want to modify it [y/n]?").ToUpper().Trim()
if($yesNo -eq "Y") {
$input = Read-Host "Enter the new value"
setHideFastUserSwitchingValue($input)
$hideFastUserSwitchingValue = getHideFastUserSwitchingValue
Write-Host "HideFastUserSwitching value is now $hideFastUserSwitchingValue"
} else {
$hideFastUserSwitchingValue = getHideFastUserSwitchingValue
Write-Host "HideFastUserSwitching value has not been modified and is equal to $hideFastUserSwitchingValue"
}

I want to display a popup message of date contains in text file

I am having a script file to compare the my system login username and samaccountname. If the system login username and samaccountname is matched then my output is display popup message of my system login username. But the below script is working fine if the data is in excel file format. Due to some of user not having the ms office. Those used are doing browser based work. So i need to read the text file if the samaccountname matches contains in text file i want display the samaccountname and date.
Sample text file screenshot
$FilePath = 'd:\Alluserreport.xlsx'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $false
$wb = $xl.Workbooks.Open($filepath)
# get data from columns 2 and 3
$sheet = $wb.Worksheets['Alluserreport']
$rowMax = $sheet.UsedRange.Rows.Count
$data = for ($row = 2; $row -le $rowMax; $row++) {
[PsCustomObject] #{
SamAccountName = $sheet.Cells.Item($row, 2).Value2
LastLogonDate = [datetime]::FromOADate($sheet.Cells.Item($row, 3).Value2) # convert to DateTime object
}
}
# cleanup
$wb.close()
$xl.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
# filter for a specific username in the data
$user = $data | Where-Object { $_.SamAccountName -eq $env:USERNAME }
if ($user) {
$msgBody = "User: {0}`r`nLastLogon: {1}" -f $user.SamAccountName, $user.LastLogonDate
$msgTitle = "Test"
$msgButton = 'OK'
$msgImage = 'Asterisk'
$Result = [System.Windows.MessageBox]::Show($msgBody,$msgTitle,$msgButton,$msgImage)
}
else {
Write-Host "Not found"
}
Thanks for accepting the previous question.
Working with CSV files is even a lot easier than getting data from Excel.
Using your example:
# import the data from the file
$data = Import-Csv -Path 'd:\Alluserreport.csv'
# filter for a specific username in the data
$user = $data | Where-Object { $_.SamAccountName -eq $env:USERNAME }
if ($user) {
$msgBody = "User: {0}`r`nLastLogon: {1}" -f $user.SamAccountName, $user.'Expiration Date'
$msgTitle = "Test"
$msgButton = 'OK'
$msgImage = 'Asterisk'
$Result = [System.Windows.MessageBox]::Show($msgBody,$msgTitle,$msgButton,$msgImage)
}
else {
Write-Host "Not found"
}

Error when checking array element in Powershell script : unexpected token 'eq'

I wish to go through a sharepoint list and if a property (a choice field named Status) is a certain value then change the author of that item.
Add-PSSnapin Microsoft.SharePoint.Powershell
$web = Get-SPWeb "http://site"
$library = $web.Lists["UserInfo"]
$newUser = $web.EnsureUser("user1")
$oldUser = $web.EnsureUser("user2")
foreach ($item in $library.Items)
{
#$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["DocumentAuthorColumnInternalName"].ToString())
$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
$login = $userfield.User.LoginName
#if ($login -eq $oldUser.LoginName)
if ($login -eq $oldUser.LoginName)
{
#if($item["Status"] eq 'Fully Implemented')
#{
$item["Author"] = $newUser
#if you are using default "Author" column, you need to set the following as well:
$item.Properties["vti_author"] = $newUser.LoginName
$item.UpdateOverwriteVersion() #this saves changes without incrementing the version
#}
}
$login = $null
}
$web.Dispose();
I can get it working but when I reach the line
if($item["Status"] eq 'Fully Implemented')
It causes an error
unexpected token 'eq'
Have you just missed the hyphen in eq? So it should be:
if($item["Status"] -eq 'Fully Implemented')
{
}

Opening a SSRS project using Powershell

I have a report that is copied to a number of different servers. It is imported manually and the data source properties are altered to match the current server's specs. I would like to be able to automate the process by enabling users to open a the SSRS report and dynamically alter it's shared data source properties through PowerShell. I hope you could help. You may see reference below.
The script would accept an input parameter for servername, username and password. Also, the save my password must be ticked.
I couldn't believe I managed to create a script for this. You may make use of the script below as future reference. Comments are available for each part and anything that needs to be altered has a "here" keyword , ex. Your_database_name_here .
Import-Module SqlPs
#Input parameter to get Server\Instancename of your Datasource
$Servername = Read-Host "Please enter your Servername"
$Instancename = Read-Host "Please enter your Instancename. For default instance please press enter"
Write-host ""
if ($Instancename -eq ""){
$ServerInstance = $Servername
}
Else {
$ServerInstance = $Servername +"\"+ $InstanceName
}
#Setting up SSRS Target URL. This is the location where your reports would be deployed.
if ($Instancename -eq ""){
$ReportServerUri = "http://$Servername/ReportServer//ReportService2010.asmx?wsdl"
$TargetURL = "http://$Servername/Reports"
}
Else {
$ReportServerUri = "http://$Servername/ReportServer_$Instancename//ReportService2010.asmx?wsdl"
$TargetURL = "http://$Servername/Reports_$Instancename"
}
$global:proxy = New-WebServiceProxy -Uri $ReportServerUri -UseDefaultCreden
#We would make use of SQL Server Authentication for the reports shared datasource so you need to supply a username and password.
Write-Host " SQL Server Authentication:"
$Username = Read-Host " Username"
$Password = Read-Host -AsSecureString "Password"
$type = $Proxy.GetType().Namespace
$datatype = ($type + '.Property')
$property =New-Object ($datatype);
$property.Name = “NewFolder”
$property.Value = “NewFolder”
$numproperties = 1
$properties = New-Object ($datatype + '[]')$numproperties
$properties[0] = $property;
$newFolder = $proxy.CreateFolder("Reports”, “/”, $properties);
$newFolder = $proxy.CreateFolder("Data Sources”, “/”, $properties);
$Children =$proxy.ListChildren("/",$false)
$DBname = 'Your_Database_Name_Here'
# Creating Datasource through powershell
Write-Host " Creating Datasource ..."
$Name = "Name_Your_Datasource_here"
$Parent = "/Data Sources"
$ConnectString = "data source=$Servername\$Instancename;initial catalog=$DBname"
$type = $Proxy.GetType().Namespace
$DSDdatatype = ($type + '.DataSourceDefinition')
$DSD = new-object ($DSDdatatype)
if($DSD -eq $null){
Write-Error Failed to create data source definition object
}
$CredentialDataType = ($type + '.CredentialRetrievalEnum')
$Cred = new-object ($CredentialDataType)
$CredEnum = ($CredentialDataType).Integrated
$Cred.value__=1
$DSD.CredentialRetrieval =$Cred
$DSD.ConnectString = $ConnectString
$DSD.Enabled = $true
$DSD.EnabledSpecified = $false
$DSD.Extension = "SQL"
$DSD.ImpersonateUserSpecified = $false
$DSD.Prompt = $null
$DSD.WindowsCredentials = $false
$DSD.UserName = $Username
$DSD.Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
$newDSD = $proxy.CreateDataSource($Name,$Parent,$true,$DSD,$null)
#Deploying RLD files to Target URL
Write-Host " Deploying RDL files ..."
$stream = Get-Content 'D:\Your_RDL_path_here.rdl' -Encoding byte
$warnings =#();
$proxy.CreateCatalogItem("Report","Report_Name_here","/Reports",$true,$stream,$null,[ref]$warnings)
#Let's make use of the datasource we just created for your RDL files.
$Items = $global:proxy.listchildren("/Data Sources", $true)
foreach ($item in $items)
{
$DatasourceName = $item.Name
$DatasourcePath = $item.Path
}
$RDLS = $global:proxy.listchildren("/Reports", $true)
foreach ($rdl in $rdls)
{
$report = $rdl.path
$rep = $global:proxy.GetItemDataSources($report)
$rep | ForEach-Object {
$proxyNamespace = $_.GetType().Namespace
$constDatasource = New-Object ("$proxyNamespace.DataSource")
$constDatasource.Name = $DataSourceName
$constDatasource.Item = New-Object ("$proxyNamespace.DataSourceReference")
$constDatasource.Item.Reference = $DataSourcePath
$_.item = $constDatasource.Item
$global:proxy.SetItemDataSources($report, $_)
Write-Host "Changing datasource `"$($_.Name)`" to $($_.Item.Reference)"
}
}
#Open a IE browser to view the report.
$IE=new-object -com internetexplorer.application
$IE.navigate2($TargetURL)
$IE.visible=$true
Write-Host ""
Write-Host "You may now view the Reports through the open IE browser."
Write-Host -ForegroundColor Green "**STEP COMPLETED!"

Powershell While loop Issue

Why does my loop only happen once? I want to enter 5 users and add it to a hashtable, but the code runs once then stops. How Do I fix it?
$userID=""
$firstname=""
$lastname="
$personCount = 1
$personHash = #{}
while ($personCount -le 5){
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$user = New-Object PSCustomObject -Property #{
ID = $userID
FirstName = $firstname
LastName = $lastname
}
$personHash.Add($user.ID,$user)
}
}
Output:
Enter ID: 1001
Enter First Name: Charles
Enter Last Name: Whitfield
Name Value
---- -----
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
1001 #{ID=1001; FirstName=Charles; LastName=Whitfield}
Your loop runs 5 times.
The problem is that once the variables are populated in the first loop, they fail the While condition in the all the subsequent loops. It runs one time, doing a read-host and setting the variables. Then it runs 4 more times, but doesn't find anything to do.
Your updated code is closer. You save the data, but didn't clear the variables for the next loop.
$userID=""
$firstname=""
$lastname=""
$personCount = 1
$personHash = #{}
while ($personCount -le 5){
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$user = New-Object PSCustomObject -Property #{
ID = $userID
FirstName = $firstname
LastName = $lastname}
$personHash.Add($user.ID,$user)
$UserID,$firstname,$lastname = ""
}
Couple of issues here, the while loops need clear variables like mjolinor said. Once that is done, I suggest saving that data in an array, so the data of each user is not lost by the next iteration:
$users = #()
$personCount = 1
while ($personCount -le 5){
$userID=""
$firstname=""
$lastname=""
$personCount++
While([string]::IsNullOrWhiteSpace($userID)){
$userID = Read-Host "Enter ID"
}
While([string]::IsNullOrWhiteSpace($firstname)){
$firstname = Read-Host "Enter First Name"
}
While([string]::IsNullOrWhiteSpace($lastname)){
$lastname = Read-Host "Enter Last Name"
}
$users += New-Object -TypeName PSCustomObject -Property #{
userID = $userID;
firstName = $firstname;
lastName = $lastname
}
}
Once the array $users has all the data, you can output all the values at once with $users or specific users with $users[0],$users[1], etc.
It's clearly not possible that the code you posted would create the output you posted. Even if I discount the two syntax errors you'd still be getting 4 key conflict exceptions, because you're trying to add the same key to the same hashtable 5 times (a key in a hashtable must be unique).
If you want to create 5 user objects in a hashtable and make sure that the user enters a value for all 3 properties you could do something like this if you want a duplicate ID to throw an error:
$personHash = #{}
1..5 | % {
do {
$userID = Read-Host "Enter ID"
$firstname = Read-Host "Enter First Name"
$lastname = Read-Host "Enter Last Name"
} until ( $userID -and $firstname -and $lastname )
$user = New-Object -Type PSCustomObject -Property #{
'ID' = $userID
'FirstName' = $firstname
'LastName' = $lastname
}
$personHash.Add($userID, $user)
}
or like this if you want a duplicate ID to update the current values:
$personHash = #{}
1..5 | % {
do {
$userID = Read-Host "Enter ID"
$firstname = Read-Host "Enter First Name"
$lastname = Read-Host "Enter Last Name"
} until ( $userID -and $firstname -and $lastname )
$user = New-Object -Type PSCustomObject -Property #{
'ID' = $userID
'FirstName' = $firstname
'LastName' = $lastname
}
$personHash[$userID] = $user
}